我在使用 Unity 应用程序块时遇到问题,我创建了一个名为 Composition 的基类。
每个组合都包含一个 IUnityContainer,当我创建顶级对象 UniversalComposition 时,我想用一个 UnityContainer 对其进行初始化。
从 UniversalComposition 创建的任何对象我想使用 IUnityContainer.CreateChildContainer 方法将子 IUnityContainer 注入其中。
class Program
{
static void Main(string[] args)
{
UniversalComposition universe = new UniversalComposition();
}
}
public class UniversalComposition : Composition
{
// Everything that gets resolved in this container should contain a child container created by the this container
public UniversalComposition()
{
this.Container.RegisterType<IService, Service>();
}
protected override IUnityContainer CreateContainer()
{
return new UnityContainer();
}
}
public abstract class Composition
{
protected IUnityContainer Container {get; private set;}
public Composition()
{
this.Container = this.CreateContainer();
}
public TInstance Resolve<TInstance>()
{
return this.Container.Resolve<TInstance>();
}
protected abstract IUnityContainer CreateContainer();
}
public class Service : Composition, IService
{
public Service(/* I want to inject a child Unity Container in here container.CreateChildContainer() */)
{
}
}
public interface IService { }