本文介绍了内部类型的统一1.2依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在通过一个简单的界面提供了一些复杂的功能库的外观。我的问题是我怎么做依赖注入在外墙使用的内部类型。比方说,我的C#库code样子 -

I have a facade in a library that exposes some complex functionality through a simple interface. My question is how do I do dependency injection for the internal types used in the facade. Let's say my C# library code looks like -

public class XYZfacade:IFacade
{
    [Dependency]
    internal IType1 type1
    {
        get;
        set;
    }
    [Dependency]
    internal IType2 type2
    {
        get;
        set;
    }
    public string SomeFunction()
    {
        return type1.someString();
    }
}

internal class TypeA
{
....
}
internal class TypeB
{
....
}

和我的网站,code是一样 -

And my website code is like -

 IUnityContainer container = new UnityContainer();
 container.RegisterType<IType1, TypeA>();
 container.RegisterType<IType2, TypeB>();
 container.RegisterType<IFacade, XYZFacade>();
 ...
 ...
 IFacade facade = container.Resolve<IFacade>();

下面facade.SomeFunction()抛出,因为facade.type1异常和facade.type2为空。任何帮助是AP preciated。

Here facade.SomeFunction() throws an exception because facade.type1 and facade.type2 are null. Any help is appreciated.

推荐答案

注射内部类是不推荐的做法。

Injecting internal classes is not a recommended practice.

我想创造一个内部实现声明可以用于实例化这些类型的程序集的公共工厂类:

I'd create a public factory class in the assembly which the internal implementations are declared which can be used to instantiate those types:

public class FactoryClass
{
   public IType1 FirstDependency
   {
     get
     {
       return new Type1();
     }
   }

   public IType2 SecondDependency
   {
     get
     {
       return new Type2();
     }
   }
 }

和在XYZFacade的依赖将与FactoryClass类:

And the dependency in XYZFacade would be with the FactoryClass class:

public class XYZfacade:IFacade
{
   [Dependency]
   public FactoryClass Factory
   {
      get;
      set;
   }
}

如果你想让它可测试创造了FactoryClass的接口。

If you want to make it testable create an interface for the FactoryClass.

这篇关于内部类型的统一1.2依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-02 03:51