我有一個統一容器,並使用RegisterType
註冊以下存儲庫和實施者使用ContainerControlledLifetimeManager
。如何在主容器中註冊類型,但在子容器中解析?
public interface IPersonRepository
{
Person GetByID(ObjectSpace objectSpace, int id);
}
使用這個模式我可以有多個線程(這是一個Web應用程序)使用相同的庫實例,同時儘管每個線程使用不同的ObjectSpace
(這是一個本地緩存+從DB +一個工作單元中獲取對象的機制等)。但是,這讓我覺得很「髒」,而不是好樣的:-)
我真的很想爲:
public interface IPersonRepository
{
Person GetByID(int id);
}
要做到這一點,我將不得不創建一個子容器和使用RegisterInstance
來註冊我的ObjectSpace
。這隻要做工精細,我可以:
- 註冊
IPersonRepository
在子容器代替 - 變化壽命經理
TransientLifetimeManager
我不想做任何。 (1)僅僅是太多的工作,我想在父容器中註冊一次,然後再沒有更多。 (2)可以工作,但如果有很多依賴關係,那麼所有這些都必須是短暫的,這會導致每次需要人員存儲庫時會創建大量實例。
所以我的問題是:有沒有辦法在父級註冊類型,但有一個容器生存期實例解析並存儲在子容器而不是父容器?也許有一種方法使用自定義的生命期管理器或什麼?
我想實現的是:
UnityContainer unityContainer = new UnityContainer();
//Might be a custom manager or something
unityContainer.RegisterType<IPersonRepository, PersonRepository>
(new ContainerControlledLifetimeManager());
using (var childContainer = unityContainer.CreateChildContainer())
{
childContainer.RegisterInstance<ObjectSpace>(new MyObjectSpace());
//01 Resolves a new instance inside the child container
var repository = childContainer.Resolve<IPersonRepository>();
//02 resolves same instance as 01
repository = childContainer.Resolve<IPersonRepository>();
}
using (var childContainer = unityContainer.CreateChildContainer())
{
childContainer.RegisterInstance<ObjectSpace>(new MyObjectSpace());
//03 Resolves a new instance inside the child container
var repository = childContainer.Resolve<IPersonRepository>();
//04 resolves same instance as 03
repository = childContainer.Resolve<IPersonRepository>(); //Resolves the same instance
}