管理UnitOfWork的AutoFac对象创建 [英] Managing AutoFac object creation for UnitOfWork

查看:191
本文介绍了管理UnitOfWork的AutoFac对象创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是体系结构的新手,我正在端到端学习和设计应用程序.我具有以下架构,并且正在使用Autofac来管理对象创建.

I am new to architecture, I am in the process of learning and designing an application end to end. I have the below architecture and am using Autofac to manage object creation.

已在webapi启动上设置了所有businessobject合同,这是唯一可以实际启动我所有autofac配置/模块的启动.

All businessobject contracts have been setup on webapi startup and that is the only startup which can actually startup all my autofac configurations/modules.

我使用UnitOfWork/Repository模式,它位于我的业务层之外,我不想在WebAPi中引用UnitOfWork,但否则无法启动UnitOfWork.

I use UnitOfWork/Repository pattern and it resides beyond my business layer, I do not want to refer the UnitOfWork in my WebAPi but i cannot startup UnitOfWork otherwise.

有人可以给我一些有关我的体系结构/设计/autofac工作单元实现的输入吗?

Can someone please give me some inputs on what should be my architecture/design/autofac unitofwork implementation?

推荐答案

在App_start中注册Web项目特定的依赖项(控制器等).在BL层中有一个静态方法来注册工作单元,存储库等.在所有Web依赖项都按如下方式注册后,在App_start中调用此静态方法:

In App_start register web project specific dependencies (controllers, etc). Have a static method in BL layer which registers unit of work, repositories, etc. Call this static method in App_start when all the web dependencies are being registered as below:

//App_Start (web project)
var builder = new ContainerBuilder();
var config = GlobalConfiguration.Configuration;
MyProject.BusinessLayer.RegisterDependancies.Register(builder); <-- Register Unit of Work here in static BL method
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterApiControllers(typeof(MvcApplication).Assembly);
builder.RegisterModule<AutofacWebTypesModule>();
builder.RegisterWebApiFilterProvider(config);
builder.RegisterModule(new AutofacModules.AutoMapperModule());
builder.RegisterModule(new AutofacModules.Log4NetModule());

var container = builder.Build();

DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);


//Static method in BL
namespace MyProject.BusinessLayer
{
    public static class RegisterDependancies
    {
        public static void Register(ContainerBuilder builder)
        {
            builder.RegisterType<MyContext>().As<IDataContextAsync>().InstancePerLifetimeScope();
            builder.RegisterType<UnitOfWork>().As<IUnitOfWorkAsync>().InstancePerLifetimeScope();
            builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepositoryAsync<>)).InstancePerLifetimeScope();
            builder.RegisterAssemblyTypes(typeof(BusinessService).Assembly).Where(t => t.Name.EndsWith("Service")).AsImplementedInterfaces().InstancePerLifetimeScope();
        }
    }
}

这篇关于管理UnitOfWork的AutoFac对象创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆