【发布时间】:2011-03-03 09:39:33
【问题描述】:
Unity(任何版本)是否提供类似于here 所述的 Ninject 自定义提供程序?我需要在类型解析时访问上下文信息。具体来说,我需要访问调用解析的类型。
【问题讨论】:
标签: dependency-injection unity-container ioc-container ninject
Unity(任何版本)是否提供类似于here 所述的 Ninject 自定义提供程序?我需要在类型解析时访问上下文信息。具体来说,我需要访问调用解析的类型。
【问题讨论】:
标签: dependency-injection unity-container ioc-container ninject
我不确定您是否可以直接执行此操作,但我认为您可以通过执行以下操作来实现类似的效果:
public interface IMyType
{
//whatever you need
}
public interface IMyTypeProvider
{
IMyType Create(object context);
}
public class MyTypeProvider : IMyTypeProvider
{
public IMyType Create(object context)
{
//construct required instance based on context
}
}
public class ClassWhichNeedsMyType
{
public ClassWhichNeedsMyType(IMyTypeProvider provider)
{
this.myType = provider.Create(this);
}
private IMyType myType;
}
然后将提供程序注册到容器中,并使用它来构建您的依赖项:
container.RegisterType<IMyTypeProvider, MyTypeProvider>();
【讨论】: