I’m using Unity.Mvc3 in my project and it has embedded UnityDependencyResolver.
var container = BuildUnityContainer();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
and the BuildUnityContainer method looks like:
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer()
.RegisterType<IControllerActivator, HControllerActivator>()
.RegisterType<IDatabaseFactory, DatabaseFactory>(
new HierarchicalLifetimeManager())
.RegisterType<IUnitOfWork, UnitOfWork>(new HierarchicalLifetimeManager())
.RegisterType<IRepository<Article>, HRepository<Article>>()
.RegisterType<IRepository<ContentBase>, HRepository<ContentBase>>()
.RegisterType<IRepository<User>, HRepository<User>>()
.RegisterType<IRepository<Profile>, HRepository<Profile>>();
container.RegisterControllers();
return container;
}
but when I try to resolve my type like this:
var users = DependencyResolver.Current.GetService<IRepository<User>>();
I get the following exception:
Resolution of the dependency failed, type =
“Data.IRepository1[Data.Models.User]", name = "(none)". Exception1 cannot be
occurred while: while resolving. Exception is:
InvalidOperationException - The type HRepository
constructed. You must configure the container to supply this value.
What am I doing wrong? And is it actually possible to use .RegisterType<IFoo<T>, Foo<T>>()?
Maybe I need some kind of custom DependencyResolver?
Thanks in advance 🙂
What you are trying to do do should be possible. Unity may not know how to build
HRepository<T>.What does the
HRepository<T>class look like? Specifically, what are the constructor parameters and do any of their types need to be registered with Unity?Unity will not be able to resolve
HRepository<T>if it does not know how to construct its parameters.