EF data 与 Biz 解藕

  我们既要使用 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/p/2832070.html