EF data 与 Biz 解藕

本文介绍了如何在不直接暴露DbContext的情况下使用Entity Framework (EF) 和 Ninject 进行依赖注入的方法,以此来提高应用程序的解耦性和灵活性。

  我们既要使用 EF 生成的Model,然而我们又不想在 UI 层上使用 DbContext,所以我们在生成 EF Entity 的时候

image

 

将 Entity Container 访问设置 为 internal ,  这样就可以将 context进行隐藏,

如果使用 Code First 的时候 ,我们就将

image

 

context.tt 中的

 public class <#= efHost.EntityContainer.Name #> : DbContext

改为 

 internal  class <#= efHost.EntityContainer.Name #> : DbContext

 

这样都可以将 DbContext的访问进行限制。

 

下面问题来了,我们毕竟要对它们的连接进行设置的,虽然是可以通过默认的连接串进行连接的,但是我们需要更多的可控性,因为我们的程序中会有其它的要求,

所以,利用Niniject 对DbContext的构造进行注入。当然,这个是要放在一个新的项目中了, 同样也是为了解藕。

Service , 依赖于 IRepository 而非具体的实现。。。。。

 

 public class NinjectLoader : NinjectModule
    {

        public override void Load()
        {

            var kernel = this.Kernel;

            Microsoft.Practices.ServiceLocation.ServiceLocator.SetLocatorProvider(() =>
           {
               return new NinjectAdapter.NinjectServiceLocator(kernel);
           });

            Configure
                .Using(new NInjectContainerAdapter(kernel))
                .ConfigureData<EFConfiguration>(efConfig =>
                {

                    efConfig.WithObjectContext(() =>
                    {
                        var parameter =
                            new ConstructorArgument(
                                "nameOrConnectionString",
                                "GameWeiBoEntities");
                        Type intype =
                            Assembly.Load(                              "Kt.GameWeiBo.Data")
                                    .GetType(
                                        "Kt.GameWeiBo.Data.GameWeiBoEntities");
                        object entities2 =
                            kernel.Get(intype,
                                       parameter);

                        return entities2 as DbContext;
                    });
                })
                //.ConfigureState<DefaultStateConfiguration>(config => config.Configure(new NInjectContainerAdapter(_kernel)))
                .ConfigureState<DefaultStateConfiguration>()

                //.ConfigureUnitOfWork<DefaultUnitOfWorkConfiguration>(x => x.AutoCompleteScope())
                ;


        }

    }

转载于:https://www.cnblogs.com/zbw911/archive/2012/12/25/2832070.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值