系列目录
很多人问我如何用配置文件来配置注入,本节演示如何利用配置文件来注入,道理是一样的,跳转到上一节下载源码一起来动手!
1.打开源码定位到文件DependencyRegisterType.cs
红框部分是必须的,接口和实现的命名空间,程序集,类,所以我们的配置文件也需要拥有以上属性
2.在Apps.Web新建一个XML文件
并添加以下代码:
<?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节点啥都不写也是没有关系的,只是作为一个别名使用,我们下面全是使用真实名称
好了,准备调用!
3.修改原来Apps.Core下的UnityConfig.cs为
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; } } }
4.最后在Web网站Apps.Web的Global添加调用代码
UnityConfig.RegisterComponents();
5.运行代码
控制器代码:
public class Default1Controller : BaseController { [Dependency] public ISysPersonBLL m_BLL { get; set; } public ActionResult Index() { ViewBag.Value = m_BLL.GetValue(); return View(); } }
业务层代码:
public class SysPersonBLL:ISysPersonBLL { [Dependency] public ISysPersonRepository m_Rep { get; set; } public string GetValue() { return m_Rep.GetValue(); } }
数据访问层代码:
public partial class SysPersonRepository { public string GetValue() { return "直接到DAL"; } }
最后界面展示:
总结:
正确利用注入方式获得了数据,其实配置形式,更加麻烦,每个站点都要存在一个XML文件。而且配置容易出错,出现虽然有提示,但是如果一旦数量太多,容易出错!
代码下载:http://yunpan.cn/c6XDwfaCY9sff 访问密码 8d0e