Unity分层注入
请帮助我解决以下目标: 我有定义属性 Context 的接口 IRepository,作为示例:
interface IRepository
{
IContext Context { get; set; }
}
interface IOne : IRepository
{
}
interface ITwo : IRepository
{
}
实现中的属性 Context 具有 DependencyAttribyte 且所有实现均按以下示例注册:
container.RegisterType<IOne, One>();
container.RegisterType<ITwo, Two>();
container.RegisterType<IContext, Context>();
我想从实现“一”解析实现“二”并继承属性值“语境”;
作为示例:
public class One : IOne
{
[Dependency]
public IContext Context { get; set; }
[Dependency]
public IUnityContainer Container { get; set; }
public void Test1()
{
Context = new Context();
var two = Container.Resolve<ITwo>();
// I want that these values would been equal
Assert.AreEqual(Context, two.Context);
}
}
如果您能够展示另一种方式来解决具有值继承的实现,那就太好了。
Please help me to solve the following goal:
I have interface IRepository that defines the property Context, as a sample:
interface IRepository
{
IContext Context { get; set; }
}
interface IOne : IRepository
{
}
interface ITwo : IRepository
{
}
the property Context in implementation have DependencyAttribyte and all implementation registered as in following sample:
container.RegisterType<IOne, One>();
container.RegisterType<ITwo, Two>();
container.RegisterType<IContext, Context>();
I want to resolve implementation "Two" from implementation "One" with inheritance of value of property "Context";
as a sample:
public class One : IOne
{
[Dependency]
public IContext Context { get; set; }
[Dependency]
public IUnityContainer Container { get; set; }
public void Test1()
{
Context = new Context();
var two = Container.Resolve<ITwo>();
// I want that these values would been equal
Assert.AreEqual(Context, two.Context);
}
}
If you will able to show another way how to resolve implementations with value inheritance then it would be great.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
PerResolveLifetimeManager
。它只是一种短暂的生活方式,但实例将在整个对象图中被重用。但是,要使其正常工作,您必须替换Test1
方法中对container.Resolve
的调用。始终优先选择构造函数注入而不是属性注入,并防止从类内调用容器。这种编码方式称为服务定位器反模式。You can use the
PerResolveLifetimeManager
. It acts just as a transient lifestyle, but the instance will be reused thoughout the object graph. For this to work however, you will have to replace the call tocontainer.Resolve
from yourTest1
method. Always prefer constructor injection over property injection and prevent calling into the container from within your classes. This way of coding is called the service locator anti-pattern.您可以使用 ContainerControlledLifetimeManager 注册
IContext
。因此,每次调用Resolve
都将返回相同的实例。另一种方法是注册实例 IContext 的。
You can register
IContext
using the ContainerControlledLifetimeManager. Thus every call toResolve<IContext>
will return the same instance.Another way is to register an instance of IContext.