2011-06-02 127 views
1

夥計。 我們正在爲應用程序使用MS Unity 2框架。Unity2解決問題

我們有類似下面

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>(); 
    ... 
} 

描述我們需要描述的類上下文和SomeFlow使用Unity之間的關係的代碼。構造的問題是當容器正在構建Context對象時,它需要創建需要Context對象等的SomeFlow對象。 在我們的例子中,SomeFlow對象必須包含指向之前創建的Context對象的鏈接。所以算法必須是下一個:

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

而問題是我們怎麼能用統一來描述它呢?

回答

2

您可以使用構造函數注入來爲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);   
} 
+0

Thx,但它需要對體系結構進行一些更改。 – 2011-06-02 11:50:16

1

或者馬克的回答,您可以註冊一個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; 
})); 
+0

它看起來很方便。它可以在Xml配置文件中完成嗎? – 2011-06-02 11:49:32

+0

我不這麼認爲。 – Steven 2011-06-02 13:03:29