不少人問我如何用配置文件來配置注入,本節演示如何利用配置文件來注入,道理是同樣的,跳轉到上一節下載源碼一塊兒來動手!app
紅框部分是必須的,接口和實現的命名空間,程序集,類,因此咱們的配置文件也須要擁有以上屬性網站
並添加如下代碼:ui
<?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/> </configSections> <unity> <alias alias="" type="" /> <namespace name="Apps.IBLL" /> <namespace name="Apps.BLL" /> <namespace name="Apps.IDAL" /> <namespace name="Apps.DAL" /> <assembly name="Apps.IBLL" /> <assembly name="Apps.BLL" /> <assembly name="Apps.IDAL" /> <assembly name="Apps.DAL" /> <container> <register type="ISysPersonBLL" mapTo="SysPersonBLL" /> <register type="ISysPersonRepository" mapTo="SysPersonRepository" /> </container> </unity> </configuration>
其實alias節點啥都不寫也是沒有關係的,只是做爲一個別名使用,咱們下面全是使用真實名稱spa
好了,準備調用!3d
using Microsoft.Practices.Unity; using Microsoft.Practices.Unity.Configuration; using System.Configuration; using System.Web; using System.Web.Http; using System.Web.Mvc; using Unity.WebApi; namespace Apps.Core { public static class UnityConfig { public static void RegisterComponents() { var container = BuildUnityContainer(); DependencyResolver.SetResolver(new UnityDependencyResolver(container)); GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container); } /// <summary> /// Builds the unity container. /// </summary> /// <returns></returns> private static IUnityContainer BuildUnityContainer() { var container = new UnityContainer(); var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = HttpContext.Current.Server.MapPath("~/Unity.Config") }; Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); var unitySection = (UnityConfigurationSection)configuration.GetSection("unity"); container.LoadConfiguration(unitySection); return container; } } }
UnityConfig.RegisterComponents();
控制器代碼:code
public class Default1Controller : BaseController { [Dependency] public ISysPersonBLL m_BLL { get; set; } public ActionResult Index() { ViewBag.Value = m_BLL.GetValue(); return View(); } }
業務層代碼:xml
public class SysPersonBLL:ISysPersonBLL { [Dependency] public ISysPersonRepository m_Rep { get; set; } public string GetValue() { return m_Rep.GetValue(); } }
數據訪問層代碼:htm
public partial class SysPersonRepository { public string GetValue() { return "直接到DAL"; } }
最後界面展現:blog
正確利用注入方式得到了數據,其實配置形式,更加麻煩,每一個站點都要存在一個XML文件。並且配置容易出錯,出現雖然有提示,可是若是一旦數量太多,容易出錯!
代碼下載:http://yunpan.cn/c6XDwfaCY9sff 訪問密碼 8d0e