hale
发布于 2023-08-02 / 55 阅读 / 0 评论 / 0 点赞

Autofac的简单使用

官方文档: Welcome to Autofac’s documentation! — Autofac 6.0.0 documentation

控制台的使用:

// Create your builder.
var builder = new ContainerBuilder();

// Usually you're only interested in exposing the type
// via its interface:  只能使用 scope.Resolve<IService>() 解析服务
builder.RegisterType<SomeType>().As<IService>();

// However, if you want BOTH services (not as common)
// you can say so:  可以使用 scope.Resolve<SomeType>() 和 scope.Resolve<IService>() 解析服务
builder.RegisterType<SomeType>().AsSelf().As<IService>();

// 带生命周期的解析服务
// Create the scope, resolve your IDateWriter,
// use it, then dispose of the scope.
using (var scope = Container.BeginLifetimeScope())
{
    var writer = scope.Resolve<IDateWriter>();
    writer.WriteDate();
}

使用工厂方法注册服务

// Create the builder with which components/services are registered.
var builder = new ContainerBuilder();

// Register types that expose interfaces...
builder.RegisterType<ConsoleLogger>().As<ILogger>();

// Register instances of objects you create...
var output = new StringWriter();
builder.RegisterInstance(output).As<TextWriter>();

// Register expressions that execute to create objects...
builder.Register(c => new ConfigReader("mysection")).As<IConfigReader>();

// Build the container to finalize registrations
// and prepare for object resolution.
var container = builder.Build();

// Now you can resolve services using Autofac. For example,
// this line will execute the lambda expression registered
// to the IConfigReader service.
using(var scope = container.BeginLifetimeScope())
{
  var reader = scope.Resolve<IConfigReader>();
}

使用反射注册

var builder = new ContainerBuilder();
builder.RegisterType<ConsoleLogger>();
builder.RegisterType(typeof(ConfigReader));

使用程序集实现批量注册

var dataAccess = Assembly.GetExecutingAssembly();

builder.RegisterAssemblyOpenGenericTypes(dataAccess)
       .Where(t => t.Name.StartsWith("MessageHandler"))
       .AsImplementedInterfaces();
       
// Autofac doc - http://autofac.readthedocs.io
//程序结构级别注入
//Register Framework Dependency.
builder.RegisterAssemblyTypes(assemblies)
    .PropertiesAutowired()
    .Where(type => typeof(IController).IsAssignableFrom(type) && !type.GetTypeInfo().IsAbstract);

builder.RegisterAssemblyTypes(assemblies)
    .PropertiesAutowired()
    .Where(type => typeof(ITransientDependency).IsAssignableFrom(type) && !type.GetTypeInfo().IsAbstract)
    .AsImplementedInterfaces().InstancePerLifetimeScope();

builder.RegisterAssemblyTypes(assemblies)
    .PropertiesAutowired()
    .Where(type => typeof(ISingletonDependency).IsAssignableFrom(type) && !type.GetTypeInfo().IsAbstract)
    .AsImplementedInterfaces().SingleInstance();

builder.RegisterAssemblyTypes(assemblies)
    .PropertiesAutowired()
    .Where(type => typeof(IPolymorphismDependency).IsAssignableFrom(type) && !type.GetTypeInfo().IsAbstract)
    .AsSelf().InstancePerLifetimeScope();

PropertiesAutowired() 允许属性注入

AsSelf() 将自身也注册为服务

AsImplementedInterfaces() 实现了多个接口的服务, 任何一个接口解析后都是相同的服务

InstancePerLifetimeScope() 解析后服务的生命周期为范围

SingleInstance() 解析后服务的生命周期为单例

在.netWebApi项目种的使用

// 1.继承Autofac.Module 类, 重写Load方法,在方法中注册
public class AutofacModuleEx : Autofac.Module
{
    protected override void Load(ContainerBuilder builder)
    {
        // 这里可以使用以上任何方式,注册本项目自己的所有服务
        Assembly interfaceAssembly = Assembly.Load("hale.mini.interfaces");
        Assembly serviceAssembly = Assembly.Load("hale.mini.services");
        builder.RegisterAssemblyTypes(interfaceAssembly, serviceAssembly).AsImplementedInterfaces();
    }
}

//在Program中注册如下
// 用Autofac接管注册
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
{
    builder.RegisterModule(new AutofacModuleEx());

});

评论