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? 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?

Answers


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>();

Need Your Help

Why are two cursors running and moving in an embedded applicaton at the same time?

c++ qt user-interface beagleboard

I am using qt-embedded 4.7.1. I was able to cross-compile the framework on the host machine to target the Beagleboard machine, but when I deployed and ran a demo application on this target, I saw two

Correct subclassing and reusing of UITableViewHeaderFooterView

ios objective-c uitableview reuseidentifier

I have a UITableView where I have section headers that can be tapped to expand or collapse the section. In my particular example each section only has one row, which is either visible (section expa...