autofac模块解析配置WebApi N Layer

时间:2017-01-25 09:58:39

标签: c# asp.net asp.net-mvc asp.net-web-api

我使用简单的autofac工作,但是在程序集的模块扫描选项中,它会在Web Api中抛出运行时异常。

Global.asax.cs中的简单工作代码

var builder = new ContainerBuilder();
var config = GlobalConfiguration.Configuration;
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterWebApiFilterProvider(config);
builder.RegisterType<ReportRepository>().As<IReportRepository>();
builder.RegisterType<UserRepository>().As<IUserRepository>();
....
var container = builder.Build();
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

从不同图层的装配中扫描模块

public class RepositoryModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        //var assembly = AppDomain.CurrentDomain.GetAssemblies();
        var assembly = System.Reflection.Assembly.GetExecutingAssembly();

        builder.RegisterAssemblyTypes(assembly)
                .Where(a => a.Name.EndsWith("Repository"))
                .AsImplementedInterfaces()
                .InstancePerLifetimeScope();
        base.Load(builder);
    }
}

在Global.asax.cs

var config = GlobalConfiguration.Configuration;
var builder1 = new ContainerBuilder();
builder1.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder1.RegisterWebApiFilterProvider(config);
builder1.RegisterModule(new RepositoryModule());
using (var container1 = builder1.Build())
{
    config.DependencyResolver = new AutofacWebApiDependencyResolver(container1);
}

在此查找问题或建议任何其他简单方法。

...谢谢

1 个答案:

答案 0 :(得分:0)

删除using()。你正在丢弃容器。