这是我Bootstrap
在 global.asax 中的
public class Global : HttpApplication {
void Application_Start(object sender, EventArgs e) {
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
// initiate dependency injection resolver
DependencyInjectionResolver.RegisterDependencies(typeof(Global).Assembly);
}
}
这是实现
public class DependencyInjectionResolver {
private static IContainer _container;
public static TService Resolve<TService>() {
return DependencyResolver.Current.GetService<TService>();
}
public static void RegisterDependencies(Assembly assembly) {
var builder = new ContainerBuilder();
builder.RegisterFilterProvider();
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterGeneric(typeof (Repository<>))
.As(typeof (IRepository<>))
.InstancePerHttpRequest()
.InstancePerLifetimeScope();
builder.RegisterType<LoggerService>()
.As<ILoggerService>()
.InstancePerApiRequest()
.InstancePerHttpRequest();
builder.Register(x =>
new MessageDataService(Resolve<ILoggerService>(), Resolve<IRepository<ApiRequestHistory>>()))
.As<IMessagesDataService>()
.InstancePerHttpRequest()
.InstancePerApiRequest();
#region setup
_container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(_container));
GlobalConfiguration.Configuration.DependencyResolver
= new AutofacWebApiDependencyResolver(_container);
#endregion
}
}
这是我的例外:
An error has occurred.An error occurred when trying to create a controller of type 'MessageReportController'. Make sure that the controller has a parameterless public constructor.System.InvalidOperationException at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__0.MoveNext()An error has occurred.Type 'WayToLead.Web.UI.api.MessageReportController' does not have a default constructorSystem.ArgumentException at System.Linq.Expressions.Expression.New(Type type)
at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)
at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)
at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
如何修复它以使用 WebApi 和 Mvc 控制器?