痛快-IoC

IoC的好处

降低耦合,提高开发效率

实现代码

首先加入微软示例中的两个类

namespace TongKuai.IoC
{
    /// <summary>
    /// Specifies the Unity configuration for the main container.
    /// </summary>
    public class UnityConfig
    {
        #region Unity Container
        private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
        {
            var container = new UnityContainer();
            RegisterTypes(container);
            return container;
        });

        /// <summary>
        /// Gets the configured Unity container.
        /// </summary>
        public static IUnityContainer GetConfiguredContainer()
        {
            return container.Value;
        }
        #endregion

        /// <summary>Registers the type mappings with the Unity container.</summary>
        /// <param name="container">The unity container to configure.</param>
        /// <remarks>There is no need to register concrete types such as controllers or API controllers (unless you want to 
        /// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.</remarks>
        public static void RegisterTypes(IUnityContainer container)
        {
            var fileMap = new ExeConfigurationFileMap()
            {
                ExeConfigFilename = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["UnityConfigPath"])
            };
            Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
            var unitySection = (UnityConfigurationSection)configuration.GetSection("unity");
            container.LoadConfiguration(unitySection, "TKContainer");
        }
    }
}
namespace TongKuai.IoC
{
    /// <summary>Provides the bootstrapping for integrating Unity with ASP.NET MVC.</summary>
    public static class UnityWebActivator
    {
        /// <summary>Integrates Unity when the application starts.</summary>
        public static void Start()
        {
            var container = UnityConfig.GetConfiguredContainer();

            FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
            FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(container));

            DependencyResolver.SetResolver(new UnityDependencyResolver(container));

            // TODO: Uncomment if you want to use PerRequestLifetimeManager
            // Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
        }
    }
}

新建配置文件Unity.config

<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Microsoft.Practices.Unity.Configuration"/>
  </configSections>
  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <typeAliases>
      <typeAlias  alias="IProduct" type="MvcApplication2.IBLL.IProduct, MvcApplication2.IBLL" />
      <typeAlias  alias="Product" type="MvcApplication2.BLL.Product, MvcApplication2.BLL" />
    </typeAliases>
    <containers>
      <container name="TKContainer">
        <register type="IProduct" mapTo="Product"/>
      </container>
    </containers>
  </unity>
</configuration>

最后实现类

namespace TongKuai.IoC
{
    /// <summary>
    /// IoC操作类
    /// </summary>
    public static class IoCHelper
    {
        public static IUnityContainer container = UnityConfig.GetConfiguredContainer();

        [DebuggerStepThrough]
        public static T Resolve<T>()
        {
            return container.Resolve<T>();
        }

        [DebuggerStepThrough]
        public static T Resolve<T>(string name)
        {

            return container.Resolve<T>(name);
        }

        [DebuggerStepThrough]
        public static IEnumerable<T> ResolveAll<T>()
        {
            return container.ResolveAll<T>();
        }
    }
}

我们在MVC中注册

        protected void Application_Start()
        {
            IoC.UnityWebActivator.Start();

            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
        }

到此为止可以实现了IoC

调用方法

private readonly IProduct product = IoC.IoCHelper.Resolve<IProduct>();

        private readonly IProduct product;

        public HomeController(IProduct product)
        {
            this.product = product;
        }

之前我们用Unity来IoC时需要自写Controller注入,现在微软出了Microsoft.Practices.Unity.Mvc后完全不需要了,简单代码就可以实现

这里我们用到了微软企业库中的:

                       Microsoft.Practices.Unity.Mvc  

                       Microsoft.Practices.Unity

                       Microsoft.Practices.Unity.Configuration

 

 

posted @ 2013-08-02 22:49  痛快  阅读(555)  评论(0编辑  收藏  举报