2
votes

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?

2
Why do you need this extra IMyRepository interface? - Steven
That doesn't answer the question :-) - Steven
Sorry, :) Some of specialized repositories have own methods (for example, GetMyEntityBySomeCriterias) they encapsulate querying logic... trying to answer your question I got, that actually, I could remove usage of IMyRepository with IRepository<IMyEntity>. This requires some efforts, but... is still doable... Do you think I need to go this way? Probably you would better create an answer...? - Budda

2 Answers

3
votes

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>();
1
votes
IMyRepository repository = container.Resolve<IMyRepository>();