开发者

Unity: how to resolve class through base interface

Here is my repository class:

public interface IMyRepository : IRepository<IMyEntity>{}

public class MyRepository : IMyRepository
{
...
}

Here is way to register it:

container.Register<IMyRepository, MyRepository >();

Here is the way how I want to get repository resolved:

IRepository<IMyEntity> repository = container.Resolve<IRepository<IMyEntity>>();

Attempt to resolve repository in this ways give an error:

Resolution of the dependency failed, type = "CMCore.Repository.IRepository`1[CMCore.Data.ICmCoreLog]", name = "(none)". Exception occurred while: while resolving.

Exception is: InvalidOperationException - The current type, IRepository`1[IMyEntity], is an interface and cannot be constructed. Are you missing a type mapping?

At the time of the exception, the container was:

Resolving IRepository`1[IMyEntity],(none)

What is wrong in my approach?开发者_Go百科 What is a proper way to achieve mentioned functionality?

Thanks a lot!

P.S. Sometime I want to resolve my class through the IMyRepository, sometime through IRepository. Should I register class twice?


Do:

container.RegisterType<IRepository<IMyEntity>, MyRepository>();

instead. Unity, by design, only does one level of type mapping. It's only going to look for a mapping from the type you ask, it doesn't chase down inheritance trees.

If you want it to be available both a IRepository or as IMyRepository, then just register it twice:

container.RegisterType<IRepository<IMyEntity>, MyRepository>()
    .RegisterType<IMyRepository, MyRepository>();


IMyRepository repository = container.Resolve<IMyRepository>();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜