简单注入器 - 创建模块

Simple Injector - Creating Module

我想将我的 DI 库 autofac 更改为简单的注入器。

我的业务层中有一个模块,用于保持数据访问和业务层注册的注册。我从 API 注册了这个模块。我如何使用简单的注射器做到这一点?

下面是简单的代码。

在业务层。

public class AutofacModules : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
                .Where(x => x.Name.EndsWith("Service"))
                .AsImplementedInterfaces()
                .InstancePerLifetimeScope();
    }
}

在网络中API。

builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

builder.RegisterModule(new AutofacModules());

答案可以在文档中找到:

长话短说,将您的代码更改为以下内容:

// Your module
public static class BusinessLayerBootstrapper 
{
    public static void Bootstrap(Container container)
    {
        var registrations =
            from type in Assembly.GetExecutingAssembly().GetTypes()
            where type.Name.EndsWith("Service")
            from service in type.GetInterfaces()
            select new { service, type };

        foreach (var reg in registrations) {
            container.Register(reg.service, reg.type, Lifestyle.Scoped);
    }
}

在 WebAPI 中。

container.RegisterWebApiControllers(GlobalConfiguration.Configuration);

BusinessLayerBootstrapper.Bootstrap(container);