C#依赖注入常用的几种方式

1、构造器注入
通过构造器进行依赖注入

public class MyClass 
{ 
    private IMyInterFace _myinterface; 
    public MyClass (IMyInterFace myinterface) 
    { 
        this._myinterface = myinterface; 
    } 
} 

2、Setter注入
通过属性的访问器进行依赖注入

private IMyInterFace _myinterface; 
public IMyInterFace myinterface
{ 
    get { return _myinterface; } 
    set { _myinterface = value; } 
} 

3、接口注入
通过接口实现依赖注入

public interface IMyInterFaceCace
{
    IMyInterFace myinterfacce { get; set; }
}

class MyClass : IMyInterFaceCace
{
    private IMyInterFace _myinterfacce;
    public IMyInterFace myinterfacce
    {
        get { return _myinterfacce; }
        set { _myinterfacce = value; }
    }
}

此外,通过特性、反射+配置文件、定义注入方法也可进行依赖注入,不多赘述


版权声明:本文为Chen104617590原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。