zoukankan      html  css  js  c++  java
  • ASP.NET MVC5 插件机制中插件的简单实现

    Autofac 依赖注入 ASP.NET MVC5 插件机制中插件的简单实现

    一.前言

        由于项目业务复杂,创建了多个插件并把他们放在了不同的项目中,项目使用AutoFac做的IOC;但是主项目可以注入,插件注入失败,

    没有为该对象定义无参数的构造函数。下面就一步一步注入插件项目。

    二.新建带有插件的项目

        参考:ASP.NET MVC5 插件化机制简单实现

        项目结构如下图:

        

    三.建立DomainServices类库

       新建一个ITestService接口,代码如下:

    复制代码
    namespace DomainServices
    {
        public interface ITestService
        {
            string GetData();
            string GetMainData();
        }
    }
    复制代码

        新建一个TestService类实现ITestService,代码如下:

    复制代码
    namespace DomainServices
    {
        public class TestService:ITestService
        {
            public string GetData()
            {
                return "这是插件获取的Services数据";
            }
    
            public string GetMainData()
            {
                return "这是主项目获取的Services数据";
            }
        }
    }
    复制代码

    四.autofac实现主项目注入和插件注入

        1.主项目引用autofac、autofac.Integration.Mvc

           工具->库程序包管理器->管理解决方案的NuGet程序包:

        2.主项目新建一个AutoFacBootStrapper.cs类,实现autofac注入

         代码如下:

    复制代码
    using System.IO;
    using System.Linq;
    using System.Reflection;
    using System.Web;
    using System.Web.Mvc;
    using Autofac;
    using Autofac.Integration.Mvc;
    
    namespace Web
    {
        public class AutoFacBootStrapper
        {
            public static void AutoFacInit()
            {
                var builder = new ContainerBuilder();
    
                //注册DomainServices
                var services = Assembly.Load("DomainServices");
                builder.RegisterAssemblyTypes(services, services)
                  .Where(t => t.Name.EndsWith("Service"))
                  .AsImplementedInterfaces().PropertiesAutowired();
    
                //实现插件Controllers注入
                var assemblies = new DirectoryInfo(
                         HttpContext.Current.Server.MapPath("~/App_Data/Plugins/"))
                   .GetFiles("*.dll")
                   .Select(r => Assembly.LoadFrom(r.FullName)).ToArray();
                foreach (var assembly in assemblies)
                {
                    builder.RegisterControllers(assembly).PropertiesAutowired();
                }
    
                //注册主项目的Controllers
                builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
    
                var container = builder.Build();
                DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            }
        }
    }
    复制代码

         3.启用autofac注入,在Global程序Start的地方添加AutoFacBootStrapper.AutoFacInit();

    复制代码
    using System.Web.Mvc;
    using System.Web.Optimization;
    using System.Web.Routing;
    
    namespace Web
    {
        public class MvcApplication : System.Web.HttpApplication
        {
            protected void Application_Start()
            {
                AreaRegistration.RegisterAllAreas();
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                RouteConfig.RegisterRoutes(RouteTable.Routes);
                BundleConfig.RegisterBundles(BundleTable.Bundles);
                //启用autofac注入
                AutoFacBootStrapper.AutoFacInit();
            }
        }
    }
    复制代码

    五.测试autofac注入是否成功

       1.主web的HomeController给出构造函数注入demo

    复制代码
    using System.Web.Mvc;
    using DomainServices;
    
    namespace Web.Controllers
    {
        public class HomeController : Controller
        {
            //public ITestService Service { get; set; }
            ITestService _service;
            public HomeController(ITestService service)
            {
                _service = service;
            }
    
            public ActionResult Index()
            {
                ViewBag.Show = _service.GetMainData();
                return View();
            }
        }
    }
    复制代码

    主项目的View代码:

    复制代码
    @{
        ViewBag.Title = "Home Page";
    }
    
    <div class="jumbotron">
        <h1>ASP.NET</h1>
        <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
        <p><a href="http://asp.net" class="btn btn-primary btn-large">Learn more &raquo;</a></p>
    </div>
    
    <div class="row">
       <p>这里是autofac注入的主项目:@ViewBag.Show </p> 
        @Html.ActionLink("Demo插件内容访问点击这里", "Index", "Home", new { area = "Demo" }, null)
    </div>
    复制代码

    2.插件的HomeControllers给出一个属性注入demo

      注意:autofac官网不建议使用属性注入,为了便于演示,我在AutoFacBootStrapper也加上了属性注入了。具体项目的时间建议使用构造函数注入的方式。

    复制代码
    using System.Web.Mvc;
    using DomainServices;
    
    namespace Plugin.Demo.Controllers
    {
        public class HomeController : Controller
        {
            public ITestService Service { get; set; }
    
            public ActionResult Index()
            {
                ViewBag.Show=Service.GetData();
                return View();
            }
        }
    }
    复制代码

    插件的View代码:

    <div>
        <p>ASP.NET MVC 插件化:Plugin.Demo 内容</p>
        <p>autofac注入插件:@ViewBag.Show</p>
    </div>

     3.重新生成插件,运行主项目,效果如下:

      主项目页面autofac注入成功后调用DomainServices的数据如下:

    插件:

     
    分类: ASP.NET MVC
  • 相关阅读:
    LeetCode 769. Max Chunks To Make Sorted
    LeetCode 845. Longest Mountain in Array
    LeetCode 1059. All Paths from Source Lead to Destination
    1129. Shortest Path with Alternating Colors
    LeetCode 785. Is Graph Bipartite?
    LeetCode 802. Find Eventual Safe States
    LeetCode 1043. Partition Array for Maximum Sum
    LeetCode 841. Keys and Rooms
    LeetCode 1061. Lexicographically Smallest Equivalent String
    LeetCode 1102. Path With Maximum Minimum Value
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/4700737.html
Copyright © 2011-2022 走看看