I use Unity 2.0 with asp.net mvc3 in my project. An exception is thrown when I try to configure TestEntities : ObjectContext in my Repository class.
public class UserRepository:IUser
{
//TestEntities ctx = new TestEntities();
[Dependency]
public TestEntities ctx { get; set; }
//...
}
This is the exception message:
The type TestEntities has multiple constructors of length 1. Unable to disambiguate.
XML configuration:
<?xml version="1.0" encoding="utf-8" ?>
<unity xmlns="schemas.microsoft.com/practices/2010/unity">
<container>
<register type="DomainModel.Entity.TestEntities, DomainModel"
mapTo="DomainModel.Entity.TestEntities, DomainModel">
<lifetime type="perthread"/>
</register>
<register type="DomainModel.Abstract.IUser, DomainModel"
mapTo="DomainModel.Concrete.UserRepository, DomainModel">
<lifetime type="perthread"/>
</register>
</container>
</unity>
That is completely incorrect configuration. First of all you are using per-thread lifetime. Per-thread lifetime is for scenarios where you control threading by yourselves but in ASP.NET MVC you don’t have such control. ASP.NET MVC uses thread pool internally so threads are reused for subsequent requests = your context will be reused among request and it will cause you a lot of problems. Another problem is that per-thread lifetime will not handle disposal of the context so unless you handle it yourselves (that is pretty hard if you don’t have thread lifetime under your control) your application will suffice big memory leaks.
You must use different lifetime management:
Resolveon the container but in case of dependency hierarchy the same instance will be used for all injections. You must handle context disposal yourselves.Resolve. If instance is needed more than once during dependency hierarchy it will create a new instance for each injection. You must handle context disposal yourselves.Resolveon that subcontainer instance. You must dispose subcontainer once you are finished with the request and all instances with hierarchical lifetime will be disposed as well.More about different lifetime managers is in my article.
To your problem with
TestEntitiesclass. Unity will by default try to use constructor with largest number of parameters and resolve those parameters with dependency injection. If it will find more than one such constructor it will throw this error because it doesn’t know which one to choose. Even if there will be only one you will get error because dependency for such constructor will not be resolved. You must explicitly tell Unity which constructor you want to call. This one will force Unity to use default constructor instead: