依赖注入Unity框架
依赖注入和控制反转是对同一件事情的不同描述,从某个方面讲,就是它们描述的角度不同。依赖注入是从应用程序的角度在描述,可以把依赖注入描述完整点:应用程序依赖容器创建并注入它所需要的外部资源;而控制反转是从容器的角度在描述,描述完整点:容器控制应用程序,由容器反向的向应用程序注入应用程序所需要的外部资源。
第一步:在项目中添加Unity(通过nuget直接获取)
第二步:Unity简单使用步骤
1创建容器
2注册接口映射
3获取实例
1.1通过代码方式进行注册
2.2通过配置文件方式进行注册
附源码:
web.config配置文件
<?xml version="1.0" encoding="utf-8"?> <!-- For more information on how to configure your ASP.NET application, please visit http://go.microsoft.com/fwlink/?LinkId=301880 --> <configuration> <configSections> <!-- 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" /> <section name="RedisConfig" type="MyBolg.Redis.RedisConfigInfo, MyBolg" /> <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Microsoft.Practices.Unity.Configuration"/> </configSections> <unity xmlns="http://schemas.microsoft.com/practces/2010/unity"> <containers> <!--MyContainer为自定义名称 只需要和调用时名称保持一致即可--> <container name="MyContainer"> <!--type为对象的名称,mapTo为注入对象的名称 写法为用逗号隔开两部分,一是类的全部,包括命名空间,二是程序集名称--> <register type="MyBolg.Controllers.Ilog,MyBolg" mapTo="MyBolg.Controllers.FileLog,MyBolg"> <lifetime type="singleton" /> </register> </container> </containers> </unity> <RedisConfig WriteServerList="127.0.0.1:6379" ReadServerList="127.0.0.1:6379" MaxWritePoolSize="60" MaxReadPoolSize="60" AutoStart="true" LocalCacheTime="180" RecordeLog="false"> </RedisConfig> <connectionStrings> <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-MyBolg-20170628095130.mdf;Initial Catalog=aspnet-MyBolg-20170628095130;Integrated Security=True" providerName="System.Data.SqlClient" /> <add name="mmsql" connectionString="Data Source=bds278166222.my3w.com;Initial Catalog=bds278166222_db;User ID=bds278166222;pwd=wangjun1234" /> <add name="MyBolgEntities" connectionString="metadata=res://*/EFModel.Model1.csdl|res://*/EFModel.Model1.ssdl|res://*/EFModel.Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=bds278166222.my3w.com;initial catalog=bds278166222_db;user id=bds278166222;password=wangjun1234;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /><add name="BolgModel" connectionString="data source=bds278166222.my3w.com;initial catalog=bds278166222_db;user id=bds278166222;password=wangjun1234;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" /></connectionStrings> <appSettings> <add key="webpages:Version" value="3.0.0.0" /> <add key="webpages:Enabled" value="false" /> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> </appSettings> <system.web> <authentication mode="None" /> <compilation debug="true" targetFramework="4.5.2" /> <httpRuntime targetFramework="4.5.2" /> <httpModules> <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" /> </httpModules> </system.web> <system.webServer> <modules> <remove name="FormsAuthentication" /> <remove name="ApplicationInsightsWebTracking" /> <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" /> </modules> <validation validateIntegratedModeConfiguration="false" /> </system.webServer> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" /> <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" /> </dependentAssembly> </assemblyBinding> </runtime> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> <providers> <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> </providers> </entityFramework> <system.codedom> <compilers> <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" /> <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" /> </compilers> </system.codedom> </configuration>
Ioc控制器
using Microsoft.Practices.Unity; using Microsoft.Practices.Unity.Configuration; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web; using System.Web.Mvc; namespace MyBolg.Controllers { public class IOCController : Controller { // GET: IOC public ActionResult Index() { //Unity简单步骤 //1.创建容器 //2.注册接口映射 //3.获取实例 #region 通过代码方式进行注册 //IUnityContainer parentContainer = new UnityContainer(); ////父容器可以创建子容器 //IUnityContainer childerContainer = parentContainer.CreateChildContainer(); //parentContainer.RegisterType<Ilog, MyBolg.Controllers.FileLog>(); ////给datalog在容器中起个名字,以后根据名字得到database //parentContainer.RegisterType<Ilog, MyBolg.Controllers.DateLog>("database"); //Ilog textlog = parentContainer.Resolve<Ilog>(); //string str = textlog.savaLog("这是文件日志保存的实例"); //Ilog datalog = parentContainer.Resolve<Ilog>("database"); //str += datalog.savaLog("---这是数据日志保存的实例"); //ViewBag.str = str; #endregion #region 根据配置文件方式进行依赖注入 IUnityContainer container = new UnityContainer(); UnityConfigurationSection config = (UnityConfigurationSection)ConfigurationManager.GetSection(UnityConfigurationSection.SectionName); config.Configure(container, "MyContainer"); Ilog log = container.Resolve<DateLog>(); string str = log.savaLog("这是数据日志保存的内容"); Ilog logs = container.Resolve<FileLog>(); str += logs.savaLog("---这是通过文件日志保存的文件"); ViewBag.str = str; #endregion return View(); } } public interface Ilog { string savaLog(string messgae); } public class FileLog : Ilog { public string savaLog(string messgae) { return messgae; } } public class DateLog : Ilog { public string savaLog(string messgae) { return messgae; } } }
view视图
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <div> @ViewBag.str </div> </body> </html>