有条件地选择带有structuremap的DataContext

时间:2014-11-08 10:01:34

标签: c# .net asp.net-mvc entity-framework structuremap

我已经设置了一个新的MVC项目,我正在使用structuremap来处理我的DI / IoC。我正在使用实体框架和缓存存储库,包含存储库类和EF数据上下文。

所以,(简化)我有一个 IRepository ,它由混凝土实现 - CacheRepository EFRepository EFRepository 依赖于 DataContext (DbContext), CacheRepository 依赖于 IRepository (作为持久存储库后备) ), ICachingService (所以我可以选择我的缓存提供商),然后由服务实施 IService ,这取决于许多存储库。

我的问题是我的登录数据库是不同的,具体取决于登录的网站区域(例如,管理员有一个单独的登录数据库 - 这是出于我不会在这里讨论的原因)。我有一个基本的datacontext,它包含我的所有用户表,并且继承自两个主要的datacontexts;因此,根据用户尝试登录的站点的哪个区域,指示检查哪个数据库的详细信息 - 所以我需要能够根据控制器选择datacontext或connectionstring。

有人可以根据使用structuremap实例化的控制器为我提供一些关于如何实现datacontext / connectionstring的条件选择的指导吗?

我的IoC注册表目前看起来像这样(引用其中一个datacontexts):

        For<BaseDataContext>().LifecycleIs<HttpContextLifecycle>()
        .Use(x => new AdminDataContext());

        //REPOSITORIES
        For<IDAL.Repositories.Users.IApplicationUserRepository>()
            .Use<DAL.Repositories.Users.EFApplicationUserRepository>();

        For<IDAL.Repositories.Users.IUserLoginAttemptRepository>()
            .Use<DAL.Repositories.Users.EFUserLoginAttemptRepository>();

        For<IDAL.Repositories.Users.IUserRoleRepository>()
            .Use<DAL.Repositories.Users.CacheRoleRepository>()
            .Ctor<IDAL.Repositories.Users.IUserRoleRepository>()
            .Is<DAL.Repositories.Users.EFUserRoleRepository>()
            .Ctor<IDAL.Caching.IGenericCachingService<Common.Objects.Data.Users.UserRole>>()
            .Is<DAL.Caching.HttpContextGenericCachingService<Common.Objects.Data.Users.UserRole>>();

        //SERVICES
        For<IBLL.Services.IUserService>()
            .Use<BLL.Services.UserService>();

1 个答案:

答案 0 :(得分:0)

如果不了解您的架构的大局,很难回答,但您可能会做这样的事情(SomeService代表您的业务逻辑层):

public class MyController : Controller {
    private ISomeService someService;

    public MyController(ISomeService someService){
        this.someService = someService;
    }
}

public class SomeService : ISomeService {
    private SomeContext context;

    public SomeService(SomeContext context){
        this.context = context;
    }
}

这里没什么好看的 - 只是标准的构造函数注入。在您的控制器和实体框架之间拥有该业务逻辑层是一个很好的做法,并为您提供了一个注入正确的DbContext的位置,而您的控制器无需了解实体框架。