天天看点

.NET6使用autofac依赖自动注入

1.Nuget引入以下包:

Autofac
Autofac.Extensions.DependencyInjection
Autofac.Extras.DynamicProxy      

2.需要依赖注入的程序集随便建个类,里面建个方法GetAssemblyName()获取程序集名称;

.NET6使用autofac依赖自动注入
using System.Reflection;

namespace Service
{
    public static class ServiceAutofac
    {
        /// <summary>
        /// 获取程序集名称
        /// </summary>
        /// <returns></returns>
        public static string GetAssemblyName()
        {
            return Assembly.GetExecutingAssembly().GetName().Name;
        }
    }
}      

3.Program.cs中注入autofac,需要注入的类和程序集如下:

// 以下是autofac依赖注入
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
{
     //先注入JWT
     builder.RegisterType<AuthorizeJWT>().As<IAuthorizeJWT>();//可以是其他接口和类
     // 注入Service程序集
     Assembly assembly = Assembly.Load(ServiceAutofac.GetAssemblyName());//可以是其他程序集
    builder.RegisterAssemblyTypes(assembly)
    .AsImplementedInterfaces()
    .InstancePerDependency();
});      

4.使用-构造函数:

private readonly IConfiguration _configuration;//配置
        private Authorize.IAuthorizeJWT _authorizeJWT;//认证
        private readonly ILogger<LoginController> _logger;//日志
       //依赖注入
        public LoginController(IConfiguration configuration, ILogger<LoginController> logger, Authorize.IAuthorizeJWT authorizeJWT)
        {
            _configuration = configuration;
            _logger = logger;
           _authorizeJWT=authorizeJWT;
        }      

5.使用:

/// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost]
        public string Login([FromBody]ViewModels.UserLogin user)
        {
            _logger.LogError($"{System.Reflection.MethodBase.GetCurrentMethod().Name} Args:{user.ToString()}");
            return _authorizeJWT.GetJWTBear(user);
        }