依賴注入和控制反轉是對同一件事情的不同描述,從某個方面講,就是它們描述的角度不同。依賴注入是從應用程序的角度在描述,可以把依賴注入描述完整點:應用程序依賴容器創建並注入它所需要的外部資源;而控制反轉是從容器的角度在描述,描述完整點:容器控制應用程序,由容器反向的向應用程序注入應用程序所需要的外部資源。
第一步:在項目中添加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>