C# 依赖注入Autofac UnitOfWork

C# 依赖注入Autofac UnitOfWork,c#,dependency-injection,autofac,C#,Dependency Injection,Autofac,我在的集合部分遇到以下错误 public IUnitOfWork uoW { get; set; } 下等生 public class BaseController : Controller { public IUnitOfWork uoW { get; set; } protected override void OnActionExecuting(ActionExecutingContext filterContext) {

我在的集合部分遇到以下错误

public IUnitOfWork uoW { get; set; } 
下等生

 public class BaseController : Controller
    {

        public IUnitOfWork uoW { get; set; }


        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!filterContext.IsChildAction)
                uoW.BeginTransaction();
        }

        protected override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            if (!filterContext.IsChildAction)
                uoW.Commit();
        }
    }
错误:

[ArgumentNullException: Value cannot be null.
Parameter name: controllerContext]
   System.Web.Mvc.ChildActionValueProviderFactory.GetValueProvider(ControllerContext controllerContext) +98
   System.Web.Mvc.ValueProviderFactoryCollection.GetValueProvider(ControllerContext controllerContext) +69
   System.Web.Mvc.ControllerBase.get_ValueProvider() +30

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
   System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
   System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +192
   System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +101
   System.Reflection.RuntimePropertyInfo.GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture) +61
   System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index) +21
   Autofac.Core.DefaultPropertySelector.InjectProperty(PropertyInfo propertyInfo, Object instance) +111
   Autofac.Core.Activators.Reflection.AutowiringPropertyInjector.InjectProperties(IComponentContext context, Object instance, IPropertySelector propertySelector) +437
   Autofac.Builder.<>c__DisplayClass32_0.<PropertiesAutowired>b__1(Object s, ActivatingEventArgs`1 e) +24
   System.EventHandler`1.Invoke(Object sender, TEventArgs e) +0
   Autofac.Core.Registration.ComponentRegistration.RaiseActivating(IComponentContext context, IEnumerable`1 parameters, Object& instance) +73
   Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters) +255
   Autofac.Core.Resolving.InstanceLookup.Execute() +131
   Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters) +133
   Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable`1 parameters) +44

[DependencyResolutionException: An exception was thrown while executing a resolve operation. See the InnerException for details. ---> Exception has been thrown by the target of an invocation. (See inner exception for details.)]
   Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable`1 parameters) +112
   Autofac.Core.Lifetime.LifetimeScope.ResolveComponent(IComponentRegistration registration, IEnumerable`1 parameters) +108
   Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable`1 parameters, Object& instance) +74
   Autofac.ResolutionExtensions.ResolveOptionalService(IComponentContext context, Service service, IEnumerable`1 parameters) +54
   Autofac.ResolutionExtensions.ResolveOptional(IComponentContext context, Type serviceType) +67
   Autofac.Integration.Mvc.AutofacDependencyResolver.GetService(Type serviceType) +21
   System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +41

[InvalidOperationException: An error occurred when trying to create a controller of type 'Juniper.Web.Controllers.RoleController'. Make sure that the controller has a parameterless public constructor.]
   System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +178
   System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +76
   System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +88
   System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +194
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +50
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +103
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
[ArgumentNullException:值不能为null。
参数名称:controllerContext]
System.Web.Mvc.ChildActionValueProviderFactory.GetValueProvider(ControllerContext ControllerContext)+98
System.Web.Mvc.ValueProviderFactoryCollection.GetValueProvider(ControllerContext ControllerContext)+69
System.Web.Mvc.ControllerBase.get_ValueProvider()+30
[TargetInvocationException:调用的目标已引发异常。]
System.RuntimeMethodHandle.InvokeMethod(对象目标、对象[]参数、签名符号、布尔构造函数)+0
System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(对象obj,对象[]参数,对象[]参数)+192
System.Reflection.RuntimeMethodInfo.Invoke(对象obj、BindingFlags invokeAttr、绑定器绑定器、对象[]参数、CultureInfo区域性)+101
System.Reflection.RuntimePropertyInfo.GetValue(对象obj、BindingFlags invokeAttr、绑定器Binder、对象[]索引、CultureInfo区域性)+61
System.Reflection.RuntimePropertyInfo.GetValue(对象obj,对象[]索引)+21
Autofac.Core.DefaultPropertySelector.InjectProperty(PropertyInfo PropertyInfo,对象实例)+111
Autofac.Core.Activators.Reflection.AutowiringPropertyInjector.InjectProperties(IComponentContext上下文、对象实例、IPropertySelector propertySelector)+437
Autofac.Builder.c_uu显示类32_0.b_u1(对象s,激活事件参数'1e)+24
System.EventHandler`1.Invoke(对象发送方,TEventArgs e)+0
Autofac.Core.Registration.ComponentRegistration.RaiseActivating(IComponentContext上下文,IEnumerable`1参数,对象和实例)+73
Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1参数)+255
Autofac.Core.Resolving.InstanceLookup.Execute()+131
Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope,IComponentRegistration,IEnumerable`1参数)+133
Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration,IEnumerable`1参数)+44
[DependencyResolutionException:执行解析操作时引发异常。有关详细信息,请参阅InnerException。-->调用目标已引发异常。(有关详细信息,请参阅InnerException。)]
Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration,IEnumerable`1参数)+112
Autofac.Core.Lifetime.LifetimeScope.ResolveComponent(IComponentRegistration注册,IEnumerable`1参数)+108
Autofac.ResolutionExtensions.TryResolveService(IComponentContext上下文、服务服务、IEnumerable`1参数、对象和实例)+74
Autofac.ResolutionExtensions.ResolveOptionalService(IComponentContext上下文,服务服务,IEnumerable`1参数)+54
Autofac.ResolutionExtensions.ResolveOptional(IComponentContext上下文,类型serviceType)+67
Autofac.Integration.Mvc.AutofacDependencyResolver.GetService(类型serviceType)+21
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext-RequestContext,类型controllerType)+41
[InvalidOperationException:尝试创建“Juniper.Web.Controllers.RoleController”类型的控制器时出错。请确保该控制器具有无参数公共构造函数。]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext-RequestContext,类型controllerType)+178
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext RequestContext,类型controllerType)+76
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext RequestContext,String controllerName)+88
ProcessRequestInit(HttpContextBase httpContext、IController和controller、IControllerFactory和factory)+194
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext,异步回调,对象状态)+50
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext HttpContext,异步回调,对象状态)+48
System.Web.Mvc.MvcHandler.System.Web.IHTTPassynchandler.BeginProcessRequest(HttpContext上下文,AsyncCallback cb,Object extraData)+16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()+103
System.Web.HttpApplication.ExecuteStep(IExecutionStep步骤,布尔值&同步完成)+155
DependencyConfig在DependencyConfig.cs中如下所示

private static void BuildApplicationDependencies(ContainerBuilder builder)
        {
            Assembly mvcApplicationAssembly = typeof(MvcApplication).Assembly;

            // AutoMapper
            var autoMapperProfileTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes().Where(p => typeof(Profile).IsAssignableFrom(p) && p.IsPublic && !p.IsAbstract));
            var autoMapperProfiles = autoMapperProfileTypes.Select(p => (Profile)Activator.CreateInstance(p));
            builder.Register(ctx => new MapperConfiguration(cfg =>
            {
                foreach (var profile in autoMapperProfiles)
                {
                    cfg.AddProfile(profile);
                }
            }));

            builder.RegisterGeneric(typeof(Repository<>))
   .As(typeof(IRepository<>));
            builder.RegisterType<UnitOfWork>().AsImplementedInterfaces().InstancePerLifetimeScope();
            builder.RegisterType<UnitOfWork>()
       .PropertiesAutowired();
            builder.RegisterType<RoleService>().AsImplementedInterfaces().SingleInstance();
            builder.Register(container => new RoleController(container.Resolve<IRoleService>())).AsImplementedInterfaces();
            builder.Register(container => new UserController(container.Resolve<IRoleService>(), container.Resolve<IUserService>())).AsImplementedInterfaces();

            // register the filter provider which automatically enables property injection on action filters
            builder.RegisterFilterProvider();

            // Needed to allow property injection in custom action filters.
            builder.RegisterType<ExtensibleActionInvoker>().As<IActionInvoker>().InstancePerRequest();

            // register the controllers (injecting the action invoker)
            builder.RegisterControllers(mvcApplicationAssembly).InjectActionInvoker().PropertiesAutowired(PropertyWiringOptions.PreserveSetValues);

            builder.RegisterModelBinderProvider();
        }
private static void builder应用程序依赖项(ContainerBuilder builder)
{
Assembly MVCAPApplication Assembly=类型(MVCAPApplication).Assembly;
//汽车制造商
var autoMapperProfileTypes=AppDomain.CurrentDomain.GetAssemblies().SelectMany(a=>a.GetTypes().Where(p=>typeof(Profile).IsAssignableFrom(p)和&p.IsPublic和&p.IsAbstract));
var autoMapperProfiles=autoMapperProfileTypes.Select(p=>(Profile)Activator.CreateInstance(p));
builder.Register(ctx=>newmapperconfiguration(cfg=>
{
foreach(autoMapperProfiles中的var配置文件)
{
cfg.AddProfile(profile);
}
}));
builder.RegisterGeneric(类型(存储库))
.As(类型(假定));
builder.RegisterType();
builder.RegisterType()
.属性自动连线();
builder.RegisterType().AsImplementedInterfaces().SingleInstance();
Register(container=>newrolecontroller(container.Resolve()).AsImplementedInterfaces();
注册(container=>newusercontroller(container.Resolve(),container.Resolve())).AsImplementedInterfaces();
//注册筛选器提供程序,该提供程序将自动在操作筛选器上启用属性注入
builder.RegisterFil
public class UnitOfWork : IUnitOfWork
    {
        private static readonly ISessionFactory _sessionFactory;
        private ITransaction _transaction;

        public ISession Session { get; set; }

        static UnitOfWork()
        {
            _sessionFactory = Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2008.ConnectionString(x => x.FromConnectionStringWithKey("ABCD")))
               .Mappings(m =>
                         m.FluentMappings
                         .AddFromAssemblyOf<UserMap>())
                .ExposeConfiguration(config => new SchemaUpdate(config).Execute(false, true))
                .BuildSessionFactory();
        }

        public UnitOfWork()
        {
            Session = _sessionFactory.OpenSession();
        }

        public void BeginTransaction()
        {
            _transaction = Session.BeginTransaction();
        }

        public void Commit()
        {
            try
            {
                if (_transaction != null && _transaction.IsActive)
                    _transaction.Commit();
            }
            catch
            {
                if (_transaction != null && _transaction.IsActive)
                    _transaction.Rollback();

                throw;
            }
            finally
            {
                Session.Dispose();
            }
        }

        public void Rollback()
        {
            try
            {
                if (_transaction != null && _transaction.IsActive)
                    _transaction.Rollback();
            }
            finally
            {
                Session.Dispose();
            }
        }
    }
}