C# 利用Autofac批量接口註入依賴的問題小結

背景:

  本人在一位大佬的Colder框架中看到瞭這個接口註入,然後呢就想學習一下ioc思想與di設計模式。此寫法給我的感覺就是

非常的 優雅 ,優雅永不過時。關於接口註入具體是什麼可以最後推薦的地址。話不多說,開擼。

安裝:

  打開nuget管理工具,將我下面標紅色的包都進行安裝(註:千萬別安裝錯瞭,按照名字不差的安裝)

  

使用:

  我們新建一個DI的文件夾,在文件夾中增加一個接口:IDependency.cs

namespace Coldairarrow
{
    /// <summary>
    /// 註入標記
    /// </summary>
    public interface IDependency
    {

    }
}

    先不要問問什麼後面會解釋。

    後面:其實。。就是這個依賴註入的一個原理吧。根據這個接口去找依賴的實現。

    推薦去這個地址看一下:https://www.jb51.net/article/206284.htm

    好瞭,繼續分別新建Student.cs,StudentRepository.cs,IStudentRepository.cs三個類。StudentRepository.cs裡面的具體業務根據需要自行修改,這裡是為瞭測試使用。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ByzkApi
{
    public  class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Graduation { get; set; }
        public string School { get; set; }
        public string Major { get; set; }
    }
}
using Coldairarrow;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ByzkApi
{
    public class StudentRepository : IStudentRepository,IDependency
    {
        public Student Add(Student item)
        {
            throw new NotImplementedException();
        }

        public bool Delete(int id)
        {
            throw new NotImplementedException();
        }

        public Student Get(int id)
        {
            return new Student() { Name = "張三" };
        }

        public IEnumerable<Student> GetAll()
        {
            throw new NotImplementedException();
        }

        public bool Update(Student item)
        {
            throw new NotImplementedException();
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ByzkApi
{
    public interface IStudentRepository
    {
        IEnumerable<Student> GetAll();
        Student Get(int id);
        Student Add(Student item);
        bool Update(Student item);
        bool Delete(int id);

    }
}

註意:這裡好好看一下StudentRepository 是實現瞭兩個接口分別是 IStudentRepositoryIDependency(註入標記)

最關鍵的地方來瞭,我們打開項目啟動的函數Application_Start,然後註入一下接口依賴。

using Autofac;
using Autofac.Extras.DynamicProxy;
using Autofac.Integration.Mvc;
using Autofac.Integration.WebApi;
using ByzkApi.Controllers;
using ByzkApi.Interface;
using Coldairarrow;
using Microsoft.Extensions.DependencyInjection;
using System.Linq;
using System.Reflection;
using System.Web.Compilation;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace ByzkApi
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            //初始化Autofac
            InitAutofac(GlobalConfiguration.Configuration);


            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }




        private void InitAutofac(HttpConfiguration config)
        {
            var builder = new ContainerBuilder();


            var baseType = typeof(IDependency);

            //可以進行篩選如: Where(x => x.FullName.Contains("Coldairarrow"))
            var assemblys = BuildManager.GetReferencedAssemblies().Cast<Assembly>()
                .ToList();

            //自動註入IDependency接口,支持AOP,生命周期為InstancePerDependency
            builder.RegisterAssemblyTypes(assemblys.ToArray())
                .Where(x => baseType.IsAssignableFrom(x) && x != baseType)
                .AsImplementedInterfaces()
                .PropertiesAutowired()
                .InstancePerDependency()
                .EnableInterfaceInterceptors()
                .InterceptedBy(typeof(Interceptor));

            //註冊Controller
            builder.RegisterControllers(assemblys.ToArray())
                .PropertiesAutowired();
            builder.RegisterApiControllers(assemblys.ToArray()).PropertiesAutowired();
       
            //AOP
            builder.RegisterType<Interceptor>();
            builder.RegisterWebApiFilterProvider(config);

            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            var resolver = new AutofacWebApiDependencyResolver(container);
            GlobalConfiguration.Configuration.DependencyResolver = resolver;
            AutofacHelper.Container = container;
        }

    }
}

到此為止就已經註入完成瞭~

使用:

    這個接口註入好瞭之後可以在普通的Controller使用,也可以在apiController進行使用,分別看一下效果,結束。

 Controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ByzkApi.Controllers
{
    public class HomeController : Controller
    {
        readonly IStudentRepository repository;
        //構造器註入
        public HomeController(IStudentRepository repository)
        {
            this.repository = repository;
        }



        public ActionResult Index()
        {

            var a = repository.Get(1);

            ViewBag.Title = a.Name;

            return View();
        }
    }
}

  ApiController:(如果想要多個接口隻需要實現接口的時候進行繼承IDependency就可)

using ByzkApi.Interface;
using Coldairarrow.Web;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Http;

namespace ByzkApi.Controllers
{
    public class TestApiController : ApiController
    {
        readonly IStudentRepository repository;

        public ITest _test { get; }
        //構造器註入
        public TestApiController(IStudentRepository repository, ITest test)
        {
            this.repository = repository;
            _test = test;
        }

        [HttpGet]
        public DataTable test(string sql)
        {
            repository.Get(1);
            var data = _test.GetTest("sql 語句");
            //repository.GetTest(sql);
            return data;
        }
    }
}

到此這篇關於C# 利用Autofac批量接口註入依賴的文章就介紹到這瞭,更多相關C# Autofac批量註入內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: