我在
的设置部分收到以下错误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
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();
}
UnitOfWork.cs:
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();
}
}
}
}