我有一个统一容器,用于RegisterType注册以下存储库和实现者,使用ContainerControlledLifetimeManager.
public interface IPersonRepository
{
Person GetByID(ObjectSpace objectSpace, int id);
}
使用这种模式,我可以让多个线程(它是一个 Web 应用程序)同时使用同一个存储库实例,尽管每个线程都使用不同的ObjectSpace(这是一个本地缓存 + 用于从数据库中获取对象的机制 +一个工作单元等)。但这让我觉得“肮脏”,而不是那种好:-)
我真正想要的是:
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
}