• ASP.NET Core中使用Autofac进行属性注入


    一些无关紧要的废话:

      作为一名双修程序员(自封的),喜欢那种使用Spring的注解形式进行依赖注入或者Unity的特性形式进行依赖注入,当然,形式大同小异,但结果都是一样的,通过属性进行依赖注入。

      ASP.NET Core中使用了自带的Dependency Injection作为了默认的IOC容器,当然有先天的优势,很多还是喜欢切换到Autofac作为IOC容器,Unity在.Net Core中还是有很大的优势的,但据我所知,Unity5已经由微软转交到基金会了,而且本身文档很少,翻译文档以及研究的就更加少了。

      当然,说了一堆废话,Autofac本身也是支持属性注入的,但是很多还是使用构造器进行注入,我本身也是推荐使用构造器进行注入(其实我不是这么想的),因为使用属性进行注入,将会暴露当前类的属性(Autofac属性注入属性必须为public),Spring可以用private进行注入的,但是不知道为什么,Autofac我使用private的时候注入进来的时候是null,如果文章有错误的话,希望高手能在留言处指出,帮助我及更多人进步。谢谢。

    ⒈新建一个ASP.NET Core MVC程序。

    ⒉添加 NuGet 包

    Install-Package Autofac
    Install-Package Autofac.Extensions.DependencyInjection

    ⒊新建实体类,服务抽象,服务实现。(DAL我这里就省略了,自行脑部)

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace DapperDemo.Models
    {
        public class User
        {
            public int id { get; set; }
            public string username { get; set; }
            public string password { get; set; }
            public int enabled { get; set; }
        }
    }
    using DapperDemo.Models;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace DapperDemo.Services
    {
        public interface IUserService
        {
            IList<User> GetUsers();
        }
    }
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using DapperDemo.Models;
    
    namespace DapperDemo.Services.Impl
    {
        public class UserService : IUserService
        {
            public IList<User> GetUsers()
            {
                return new List<User>
                {
                    new User
                    {
                        id = 1,
                        username = "fanqi",
                        password = "admin",
                        enabled = 1
                    }
                };
            }
        }
    }

    ⒋新建一个Aufofac Module,配置注入

    using Autofac;
    using DapperDemo.Services;
    using DapperDemo.Services.Impl;
    using Microsoft.AspNetCore.Mvc;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Threading.Tasks;
    
    namespace DapperDemo.Module
    {
        public class DefaultModule : Autofac.Module
        {
            protected override void Load(ContainerBuilder builder)
            {
    
                builder.RegisterType<UserService>().As<IUserService>().PropertiesAutowired()
                    .InstancePerLifetimeScope();
    
                var controllersTypesInAssembly = typeof(Startup).Assembly.GetExportedTypes()
                    .Where(type => typeof(ControllerBase).IsAssignableFrom(type)).ToArray();
                builder.RegisterTypes(controllersTypesInAssembly).PropertiesAutowired();
    
            }
        }
    }

    ⒌修改Startup,替换IOC,使用Autofac作为默认的IOC容器

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Threading.Tasks;
    using Autofac;
    using Autofac.Extensions.DependencyInjection;
    using DapperDemo.Module;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    
    namespace DapperDemo
    {
        public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
    
            // This method gets called by the runtime. Use this method to add services to the container.
            public IServiceProvider ConfigureServices(IServiceCollection services)
            {
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddControllersAsServices();
                
                // 添加 Autofac
                var containerBuilder = new ContainerBuilder();
    
                containerBuilder.Populate(services);
    
                containerBuilder.RegisterModule<DefaultModule>();
    
                var container = containerBuilder.Build();
    
                return new AutofacServiceProvider(container);
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                }
    
                app.UseStaticFiles();
                app.UseCookiePolicy();
    
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
            }
        }
    }

    ⒍新建控制器,在属性中注入服务抽象实现。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using DapperDemo.Models;
    using DapperDemo.Services;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;

    namespace DapperDemo.Controllers
    {
        [Route("api/[controller]")]
        [ApiController]
        public class UserController : ControllerBase
        {
            public IUserService UserService { protected get; set; }

            [Route("get")]
            public IList<User> GetUsers()
            {
                return UserService.GetUsers();
            }

        }
    }

    ⒎测试

  • 相关阅读:
    【转】linux清屏的几种方法
    【转】Ubuntu 64位系统安装交叉编译环境一直提醒 没有那个文件或目录
    【转】无法获得锁 /var/lib/dpkg/lock
    层级原理图设计方法
    【转】gcc 编译使用动态链接库和静态链接库
    【转】设置 vim 显示行号永久有效
    【转】VMware 全屏显示
    emwin之自绘制 BUTTON 图形的一些问题
    使用 sizeof 获取字符串数组的大小
    emwin之2D图形流位图显示的方法
  • 原文地址:https://www.cnblogs.com/netcs/p/12194883.html
Copyright © 2020-2023  润新知