避免容器。在简单的工厂中解决?

时间:2016-03-07 12:25:56

标签: c# dependency-injection unity-container

Unity& amp;的新手DI。我把容器放到了我的视图模型中。当我想要一个我现在知道的新视图实例是不好的做法时,调用.Resolve。

我现在通过一个简单的工厂类来解析视图,该工厂类作为接口传递给视图模型构造函数:

this.dialogView = this.dialogViewFactory.CreateDialogView();

我在Unity中调用RegisterType来解析视图&视图模型:

this.unityContainer.RegisterType(typeof(IDialogView), typeof(DialogView));
this.unityContainer.RegisterType(typeof(IDialogViewModel), typeof(DialogViewModel));
this.unityContainer.RegisterType(typeof (IDialogViewFactory), typeof (DialogViewFactory));

最后,我的工厂班。我目前正在通过集装箱和在这里呼唤决心。我知道虽然我已将依赖项移出视图模型,但我仍然在工厂类中拥有容器依赖项:

public class DialogFactory : IDialogFactory
{
    private IUnityContainer unityContainer;

    public DialogFactory(IUnityContainer unityContainer)
    {
        this.unityContainer = unityContainer;
    }

    public IDialogView CreateDialogView()
    {
        return this.unityContainer.Resolve<IDialogView>();
    }
}

最佳解决方案是什么?

1 个答案:

答案 0 :(得分:0)

您可以使用Unity Automatic Factories通过注入Func<IDialogView>来消除对工厂的需求:

public class ViewModel
{
    private Func<IDialogView> dialogViewFactory;

    public ViewModel(Func<IDialogView> dialogViewFactory)
    {
        this.dialogViewFactory = dialogViewFactory;
    }

    private IDialogView CreateDialogView()
    {
        return this.dialogViewFactory();
    }
}

如果你想要/需要一个正式的工厂,你也可以使用这种方法注入DialogFactory本身:

public class DialogFactory : IDialogFactory
{
    private Func<IDialogView> dialogViewFactory;

    public DialogFactory(Func<IDialogView> dialogViewFactory)
    {
        this.dialogViewFactory = dialogViewFactory;
    }

    public IDialogView CreateDialogView()
    {
        return this.dialogViewFactory();
    }
}