三种依赖注入方法,构造器注入、属性注入、方法注入
可以配置Config文件,来实现不用修改代码。需要先将接口与实体关联,然后使用时会自动加载对应实体。
namespace WeChatConsole
{
internal class Program
{
private static void Main(string[] args)
{
#region 构造器注入,需要在构造函数中传递抽象参数 UnityContainer container = new UnityContainer();
container.RegisterType<IWaterTool, Press2Water>(); //依赖注入
//container.RegisterType<IWaterTool, Press2Water>(); //重复注入会替换
IPeople people = container.Resolve<VillagePeople>(); //返回
people.DrinkWater();
#endregion #region 属性注入
IPeople people2 = container.Resolve<Village2People>(); //返回
people2.DrinkWater();
#endregion #region 读取配置文件
UnityContainer container2 = new UnityContainer();
UnityConfigurationSection configuration = ConfigurationManager.GetSection(UnityConfigurationSection.SectionName) as UnityConfigurationSection;
configuration.Configure(container2, "WeChatContatiner");
IPeople people3 = container2.Resolve<Village2People>(); //返回
people3.DrinkWater();
#endregion Console.Read();
}
}
//人
interface IPeople
{
void DrinkWater();
}
//村民
class VillagePeople : IPeople
{
IWaterTool _pw;
public VillagePeople(IWaterTool pw)
{
_pw = pw;
}
public void DrinkWater()
{
Console.WriteLine(_pw.returnWater());
}
}
class Village2People : IPeople
{
[Dependency] //属性注入模式
public IWaterTool _pw { get; set; } [InjectionMethod] //方法注入模式
public void DrinkWater()
{
Console.WriteLine(_pw.returnWater() + " 第二版");
}
}
//水
interface IWaterTool
{
string returnWater();
}
//压水井
class PressWater : IWaterTool
{
public string returnWater()
{
return "压水井执行方法";
}
}
class Press2Water : IWaterTool
{
public string returnWater()
{
return "压水井2执行方法";
}
}
}
配置文件如下:
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Microsoft.Practices.Unity.Configuration" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
</startup>
<unity>
<container name="WeChatContatiner">
<register type="WeChatConsole.IWaterTool,WeChatConsole" mapTo="WeChatConsole.Press2Water,WeChatConsole" />
</container>
</unity>
在看一个例子
public static class Program
{
public static void Main(string[] args)
{
IUnityContainer container = new UnityContainer();
UnityConfigurationSection configuration = ConfigurationManager.GetSection(UnityConfigurationSection.SectionName) as UnityConfigurationSection;
configuration.Configure(container, "defaultContainer");
A a = container.Resolve<IA>() as A;
if (a != null)
{
Console.WriteLine("a.B=" + a.B == null ? "Y" : "N");
Console.WriteLine("a.C=" + a.C == null ? "Y" : "N");
Console.WriteLine("a.D=" + a.D == null ? "Y" : "N");
}
Console.ReadKey();
}
} public interface IA { }
public interface IB { }
public interface IC { }
public interface ID { }
public class A : IA
{
public IB B { get; set; } [Dependency]
public IC C { get; set; } public ID D { get; set; } public A(IB b)
{
this.B = b;
} [InjectionMethod]
public void Initialize(ID d)
{
this.D = d;
}
}
public class B : IB { };
public class C : IC { };
public class D : ID { };
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,
Microsoft.Practices.Unity.Configuration" />
</configSections>
<unity>
<containers>
<container name="defaultContainer">
<register type="ConsoleApplication1.IA,ConsoleApplication1" mapTo="ConsoleApplication1.A,ConsoleApplication1" />
<register type="ConsoleApplication1.IB,ConsoleApplication1" mapTo="ConsoleApplication1.B,ConsoleApplication1" />
<register type="ConsoleApplication1.IC,ConsoleApplication1" mapTo="ConsoleApplication1.C,ConsoleApplication1" />
<register type="ConsoleApplication1.ID,ConsoleApplication1" mapTo="ConsoleApplication1.D,ConsoleApplication1" />
</container>
</containers>
</unity>
</configuration>
MVC
在MVC框架下使用Unity,需要在引入Unity.MVC 这个Nuget包
然后在Global.asax.cs 中,注入依赖
UnityContainer unityContainer = new UnityContainer();
unityContainer.RegisterType<IEmployeeRepository, EmployeeRepository>();
DependencyResolver.SetResolver(new UnityDependencyResolver(unityContainer));
此时,在控制器中,就可以使用构造器注入、属性注入、方法注入了
BuildUp
可以给对象进行注入显示注入,调用此方法,我们的对象就包含注入的方法了。
IUnityContainer container = new UnityContainer();
UnityConfigurationSection configuration = ConfigurationManager.GetSection(UnityConfigurationSection.SectionName) as UnityConfigurationSection;
configuration.Configure(container, "defaultContainer");
Program pro = new Program();
container.BuildUp(pro);
pro.HttpClient();
protected void Application_PreRequestHandlerExecute(object sender,EventArgs e)
{
Page handler = HttpContext.Current.Handler as Page;
if(handler != null){
IUnityContainer container = 实体;
if(container != null){
container.BuildUp(handler.GetType(),handler);
}
}
}