【问题标题】:Unity2 resolve problemunity2解决问题
【发布时间】:2011-06-02 07:19:18
【问题描述】:

伙计们。 我们正在为应用程序使用 MS Unity 2 框架。

我们有类似于下面描述的代码

public class Context:IContext
{
    public IFlow Flow {get;set;}
}

public class SomeFlow:IFlow
{
    public IContext Context {get;set;}
}
...
//Some code for getting IContext object
{
     ...
     IContext context = container.Resolve<IContext>();
     ...
}

我们需要使用 Unity 来描述类 Context 和 SomeFlow 之间的关系。构造的问题是,当容器构造 Context 对象时,它需要创建 SomeFlow 对象,该对象需要 Context 对象等等。 在我们的例子中,SomeFlow 对象必须包含指向之前创建的 Context 对象的链接。所以算法一定是next:

1. Create Context object
2. Create SomeFlow object
3. Point Context.Flow to SomeFlow
4. Point SomeFlow.Context to Context

问题是我们如何用统一来描述它?

【问题讨论】:

    标签: .net inversion-of-control unity-container ioc-container


    【解决方案1】:

    您可以通过构造函数注入来为 Flow 提供其上下文,然后在构造函数中设置向后引用。这是一个简单的例子:

    public interface IContext { IFlow Flow { get; set; } }
    public interface IFlow { IContext Context { get; } }
    
    public class Context : IContext
    {
        public IFlow Flow { get; set; }
    }
    
    public class SomeFlow : IFlow
    {
        public SomeFlow(IContext context)
        {
            this.Context = context;
            context.Flow = this;
        }
        public IContext Context { get; set; }
    }
    
    [Test]
    public void Example()
    {
        IUnityContainer container = new UnityContainer();
        container.RegisterType<IContext, Context>();
        container.RegisterType<IFlow, SomeFlow>();
        var flow = container.Resolve<IFlow>();
        Assert.IsInstanceOf<Context>(flow.Context);
        Assert.IsInstanceOf<SomeFlow>(flow);
        Assert.AreSame(flow, flow.Context.Flow);           
    }
    

    【讨论】:

    • 谢谢,但它需要对架构进行一些更改。
    【解决方案2】:

    除了 Mark 的回答之外,您还可以注册一个 InjectionFactory 来为您接线。注册以下委托可以避免您更改应用程序设计:

    container.Register<IContext>(new InjectionFactory(c =>
    {
        var context = container.Resolve<IContext>();
        var flow = container.Resolve<IFlow>();
        context.Flow = flow 
        flow.Context = context;
        return context;
    }));
    

    【讨论】:

    • 看起来很方便。可以在xml配置文件中完成吗?
    猜你喜欢
    • 1970-01-01
    • 2018-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2010-10-13
    • 2011-07-20
    相关资源
    最近更新 更多