0

我有一个 ASP.NET MVC 项目,其中包含 2 个数据库存储库接口 ( IDBSessionFactory) 实例:一个用于数据数据库,一个用于配置数据库。在我的引导程序中,这就是我连接 DI 的方式:

// using ...

builder.Register(c => new DbSessionFactory("dataDB", Assembly.GetExecutingAssembly()))
    .Named<IDbSessionFactory>("datadb")
    .InstancePerHttpRequest()
    .InstancePerApiRequest();

builder.Register(c => new DbSessionFactory("configDB", Assembly.GetExecutingAssembly()))
    .Named<IDbSessionFactory>("configdb")
    .InstancePerHttpRequest()
    .InstancePerApiRequest();

builder.RegisterControllers(Assembly.GetExecutingAssembly());

我有一些控制器类需要"configDB"实例IDBSessionFactory作为输入参数。我该如何实现呢?

任何帮助表示赞赏。

4

2 回答 2

2

我想到了。注册控制器时必须使用命名参数。我的策略是针对 datadb 参数注册所有控制器,然后针对 configdb 参数注册特定控制器。唯一需要注意的是在所有控制器类中保持参数名称一致。

builder.RegisterControllers(Assembly.GetExecutingAssembly()).WithParameters(new[] { 
                        new ResolvedParameter((p, c) => p.Name == "dbSessionFactory", (p, c) => c.ResolveNamed<IDbSessionFactory>("datadb")) 
                    });

// Register controllers which need a specific named type            
builder.RegisterType<Web.Controllers.AdminController>().WithParameters(new[] { new ResolvedParameter((p, c) => p.Name == "sessionFactory", (p, c) => c.ResolveNamed<IDbSessionFactory>("configdb")) });
// Wire up the account controller with the config database instance, since all the user tables are there
builder.RegisterType<Web.Controllers.AccountController>().WithParameters(new[] { 
                        new ResolvedParameter((p, c) => p.Name == "dbSessionFactory", (p, c) => c.ResolveNamed<IDbSessionFactory>("configdb")) 
                        , new ResolvedParameter((p,c) => p.Name == "logger",(p,c) => c.Resolve<ILogger>())
                        , new ResolvedParameter((p,c) => p.Name == "formsAuth",(p,c) => c.Resolve<IFormsAuthentication>())
                    });
于 2013-02-22T19:12:10.467 回答
0

在 Autofac 中,注册是最后的胜利。这意味着,在你调用之后RegisterControllers,你可以简单地对你想要覆盖的控制器进行一次性注册,它们就会生效。

例子:

builder.RegisterControllers(Assembly.GetExecutingAssembly());

builder.Register(c =>
    new FooController(c.ResolveNamed<IDbSessionFactory>("configDB")));

// ...

container.Resolve<FooController>()  // Resolves FooController with configDB
于 2013-02-21T22:55:35.630 回答