Net8 实现依赖注入(构造函数注入、属性注入)

项目以net8建立为例子(net6也通用),使用Autofac实现构造函数注入、属性注入两种。


Autofac (第三方)

1、引用以下package

Autofac
Autofac.Extensions.DependencyInjection
Microsoft.Extensions.DependencyModel

2、在program下添加autofac

builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());

3、创建实现IDependency接口,用于对引用此接口的类进行注册

public interface IDependency
{
}

4、创建实现AutoRegisterModule

public class AutoRegisterModule : Autofac.Module
{
    protected override void Load(ContainerBuilder builder)
    {
        // 自动对集成 IDependency 接口的类进行注册
        Type baseType = typeof(IDependency);
        var compilationLibrary = DependencyContext.Default.CompileLibraries.Where(x => !x.Serviceable && x.Type == "project").ToList();

        List<Assembly> assemblyList = new List<Assembly>();
        foreach (var _compilation in compilationLibrary)
        {
            try
            {
                assemblyList.Add(AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(_compilation.Name)));
            }
            catch (Exception ex)
            {
                Console.WriteLine(_compilation.Name + ex.Message);
            }
        }
        builder.RegisterAssemblyTypes(assemblyList.ToArray()).Where(type => baseType.IsAssignableFrom(type) && !type.IsAbstract)
            .AsSelf()
            .AsImplementedInterfaces() // 接口注入
            .PropertiesAutowired() // 属性注入
            .InstancePerLifetimeScope(); // scope声明周期

        var controllersTypesInAssembly = typeof(Program).Assembly.GetExportedTypes().Where(type => typeof(ControllerBase).IsAssignableFrom(type)).ToArray();

        builder.RegisterTypes(controllersTypesInAssembly).PropertiesAutowired();

    }
}

5、在program添加:

builder.Host.ConfigureContainer<ContainerBuilder>(i => i.RegisterModule<AutoRegisterModule>());
builder.Services.AddControllers().AddControllersAsServices();

Scrutor Package 小插曲

services.Scan(scan => scan
.FromAssembliesOf(typeof(Startup)) 
.AddClasses(classes => classes.Where(type => type.Name.EndsWith("Service") || type.Name.EndsWith("Repository")))
.AsImplementedInterfaces()
.WithScopedLifetime());

构造函数注入

创建service类及接口

public class TestService3 : ITestService3, IDependency
{
    public string GetString()
    {
        return "test service 3";
    }
}

public interface ITestService3
{
    string GetString();
}

在controller使用:

private readonly ITestService3 _testService3;

public WeatherForecastController(ITestService3 testService3)
{
    _testService3 = testService3;
}

[HttpGet, Route("demo")]
public string GetDemo()
{
    return _testService3.GetString();
}

属性注入

创建service类,不用创建接口也行

public class TestService2 : IDependency
{
    public string GetString()
    {
        return "test service 2";
    }
}

在controller使用:

public TestService2 service2 { get; set; } //不能写成public TestService2 service2; 这只是声明了一个变量,没有没有注入依赖项到属性中

[HttpGet, Route("demo")]
public string GetDemo()
{
    return service2.GetString();
}



posted @ 2024-02-25 11:09  Cody&  阅读(931)  评论(0编辑  收藏  举报