Reputation: 915
I'm using Unity for dependency injection.
I have a method responsible to instantiate the Database Object as follow:
container.RegisterType<DB>(
new InjectionFactory(c =>
{
return new DB();
})
);
The problem is, I have a method that use two different objects that are suposed to be referenced to the same DB instance, but look's like Unity are creating a new instance of DB Object in each injection.
Query LINQ example:
var test = from tb1 in _db1.method()
join tb2 in _db2.method() on tb1.code equals tb2.code
_db1 and _db2 reference the same DB Object as follow
DB _db = null;
public db1(DB dataContext)
{
_db = dataContext;
_db.CommandTimeout = 3600;
}
So i'm getting the following error:
The query contains references to items defined on a different data context
Could some one help me fix Unity register to reference the DB Object already instantiated instead do a new every time?
Upvotes: 0
Views: 241
Reputation: 463
You should register your db as a singleton in the container, that means each time the db is requested the same instance is returned, this:
container.RegisterType<DB>(new ContainerControlledLifetimeManager())
should do it, if this is a web application you should probably create a child container for each request there are different ways to do this, but you might want to give https://www.nuget.org/packages/Unity.Mvc4/ a try
Upvotes: 1