服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - C# 利用Autofac批量接口注入依赖的问题小结

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

2022-12-14 12:10CoolDog; C#

这篇文章主要介绍了C# 利用Autofac批量接口注入依赖的问题,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

背景:

  本人在一位大佬的Colder框架中看到了这个接口注入,然后呢就想学习一下ioc思想与di设计模式。此写法给我的感觉就是

非常的 优雅 ,优雅永不过时。关于接口注入具体是什么可以最后推荐的地址。话不多说,开撸。

安装:

  打开nuget管理工具,将我下面标红色的包都进行安装(注:千万别安装错了,按照名字不差的安装)

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

使用:

  我们新建一个DI的文件夹,在文件夹中增加一个接口:IDependency.cs

?
1
2
3
4
5
6
7
8
9
10
namespace Coldairarrow
{
    /// <summary>
    /// 注入标记
    /// </summary>
    public interface IDependency
    {
 
    }
}

    先不要问问什么后面会解释。

    后面:其实。。就是这个依赖注入的一个原理吧。根据这个接口去找依赖的实现。

    推荐去这个地址看一下:http://www.tuohang.net/article/206284.htm

    好了,继续分别新建Student.cs,StudentRepository.cs,IStudentRepository.cs三个类。StudentRepository.cs里面的具体业务根据需要自行修改,这里是为了测试使用。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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; }
    }
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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();
        }
    }
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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,然后注入一下接口依赖。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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();
        }
    }
}

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

  ApiController:(如果想要多个接口只需要实现接口的时候进行继承IDependency就可)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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批量接口注入依赖的文章就介绍到这了,更多相关C# Autofac批量注入内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.cnblogs.com/BFMC/p/15739371.html

延伸 · 阅读

精彩推荐
  • C#C#异步方法返回void与Task的区别详解

    C#异步方法返回void与Task的区别详解

    这篇文章主要给大家介绍了关于C#异步方法返回void与Task的区别的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习...

    金庆4092022-11-04
  • C#C# 创建,读取,写入XML文件

    C# 创建,读取,写入XML文件

    本篇文章主要介绍了C# 创建,读取,写入XML文件的方法,具有很好的参考价值。下面跟着小编一起来看下吧...

    lengjing1269942021-12-28
  • C#WPF实现窗体中的悬浮按钮

    WPF实现窗体中的悬浮按钮

    这篇文章主要为大家详细介绍了WPF实现窗体中的悬浮按钮,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    秋荷雨翔5982022-03-05
  • C#C#调用带结构体指针Dll的方法

    C#调用带结构体指针Dll的方法

    在C#到底该如何安全的调用这样的DLL接口函数呢?本文将详细介绍如何调用各种参数的方法,对C#结构体指针DLL相关知识感兴趣的朋友一起看看吧...

    ye_ming5602022-11-28
  • C#输出的文本实现对齐的方法(超简单)

    输出的文本实现对齐的方法(超简单)

    下面小编就为大家分享一篇c#输出的文本实现对齐的方法,特别简单!希望对大家有所帮助。一起跟随小编过来看看吧...

    杨明波(Leo Yang)11052022-02-15
  • C#C#异步调用示例详解

    C#异步调用示例详解

    这篇文章主要为大家详细介绍了C#异步调用的示例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    千年海岩11772022-01-07
  • C#C# 8.0可空引用类型的使用注意记录

    C# 8.0可空引用类型的使用注意记录

    这篇文章主要给大家介绍了关于C# 8.0可空引用类型使用注意的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用C#具有一定的参考学习价...

    自来喵的野9892022-07-19
  • C#C#简单访问SQLite数据库的方法(安装,连接,查询等)

    C#简单访问SQLite数据库的方法(安装,连接,查询等)

    这篇文章主要介绍了C#简单访问SQLite数据库的方法,涉及SQLite数据库的下载、安装及使用C#连接、查询SQLIte数据库的相关技巧,需要的朋友可以参考下...

    郑文亮5102021-11-29