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; }
    }
}

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

你可能感兴趣的:(随笔)