Autofac - 注入接口的特定实例

时间:2013-02-21 22:49:54

标签: asp.net-mvc autofac

我有一个ASP.NET MVC项目,其中包含2个数据库存储库接口(IDBSessionFactory)实例:一个用于数据数据库,另一个用于配置数据库。在我的Bootstrapper中,这就是我如何连接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实例作为输入参数。我该如何实现这一目标?

感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

我明白了。注册控制器时,必须使用命名参数。我的策略是根据datadb参数注册ALL控制器,然后根据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>())
                    });

答案 1 :(得分:0)

在Autofac中,注册是最后的胜利。这意味着,在您致电RegisterControllers后,您只需为要覆盖的控制器进行一次性注册即可生效。

示例:

builder.RegisterControllers(Assembly.GetExecutingAssembly());

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

// ...

container.Resolve<FooController>()  // Resolves FooController with configDB