C# 利用Autofac批量接口注入依赖的问题小结

 更新时间:2021年12月28日 09:56:29   作者:CoolDog;  
这篇文章主要介绍了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批量注入内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Treeview动态添加用户控件传值和取值的实例代码

    Treeview动态添加用户控件传值和取值的实例代码

    今天做了很好玩的树,是treeview与用户控件之间进行交互先看效果:
    2013-04-04
  • C# 静态变量与静态方法实例研究

    C# 静态变量与静态方法实例研究

    写了一个翻译英汉单词辞典的小程序,发现在调用几千次的时候速度很慢
    2011-11-11
  • Unity3D旧电视滤镜shader的实现示例

    Unity3D旧电视滤镜shader的实现示例

    这篇文章主要介绍了Unity3D旧电视滤镜shader的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-04-04
  • C#集合根据对象的某个属性进行去重的代码示例

    C#集合根据对象的某个属性进行去重的代码示例

    当根据对象的Name属性进行去重时,你可以使用以下三种方法:使用Distinct方法和自定义比较器、使用LINQ的GroupBy方法,以及使用HashSet,下面给大家介绍C#集合根据对象的某个属性进行去重的代码示例,感兴趣的朋友一起看看吧
    2024-03-03
  • C#实现XML文档的增删改查功能示例

    C#实现XML文档的增删改查功能示例

    这篇文章主要介绍了C#实现XML文档的增删改查功能,结合实例形式分析了xml文档的创建及C#针对xml文档的加载及增删改查等操作技巧,需要的朋友可以参考下
    2017-01-01
  • 基于C#编写一个修改文件时间属性的小工具

    基于C#编写一个修改文件时间属性的小工具

    这篇文章主要为大家详细介绍了如何基于C#编写一个修改文件时间属性的小工具,可以批量修改文件的创建时间、最后访问时间和最后修改时间,需要的可以参考下
    2024-11-11
  • C#双缓冲实现方法(可防止闪屏)

    C#双缓冲实现方法(可防止闪屏)

    这篇文章主要介绍了C#双缓冲实现方法,结合实例形式分析了C#双缓冲的具体步骤与相关技巧,可实现防止闪屏的功能,需要的朋友可以参考下
    2016-02-02
  • 在类库或winform项目中打开另一个winform项目窗体的方法

    在类库或winform项目中打开另一个winform项目窗体的方法

    这篇文章主要介绍了在类库或winform项目中打开另一个winform项目窗体的方法,可以实现Winform项目间窗体的调用,在进行Winform项目开发中非常具有实用价值,需要的朋友可以参考下
    2014-11-11
  • 详解C#中委托的概念与使用

    详解C#中委托的概念与使用

    委托这个名字取的神乎其神的,但实质是函数式编程,把函数作为参数传递给另一个参数。这篇文章主要为大家介绍一下C#中委托的概念与使用,需要的可以参考一下
    2023-02-02
  • C#机器入门学习之判断日报是否合格详解

    C#机器入门学习之判断日报是否合格详解

    这篇文章主要给大家介绍了关于C#机器入门学习之判断日报是否合格的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者使用c#具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-03-03

最新评论