使用Web API 2进行Autofac – 无参数构造函数错误
我想在我的Web API 2项目上设置Autofac。 我以前只用了几次。 我使用Nuget安装了Autofac和Autofac.WebApi2 。 然后在我的Startup课程中我做了这个:
public partial class Startup { public void Configuration(IAppBuilder app) { // Get our http configuration var config = new HttpConfiguration(); // Register the Autofac middleware FIRST. This also adds // Autofac-injected middleware registered with the container. var container = ConfigureInversionOfControl(app, config); // Register all areas AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); // Use our web api app.UseWebApi(config); } /// /// Configures Autofac DI/IoC /// /// /// private IContainer ConfigureInversionOfControl(IAppBuilder app, HttpConfiguration config) { // Create our container var builder = new ContainerBuilder(); // You can register controllers all at once using assembly scanning... builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); // Register our module builder.RegisterModule(new AutofacModule()); // Build var container = builder.Build(); // Lets Web API know it should locate services using the AutofacWebApiDependencyResolver config.DependencyResolver = new AutofacWebApiDependencyResolver(container); // Return our container return container; } }
我创建的模块如下所示:
public class AutofacModule : Module { protected override void Load(ContainerBuilder builder) { // Create our Singletons builder.RegisterType().As().InstancePerRequest(); // Create our Services builder.RegisterType().As().InstancePerRequest(); builder.RegisterType().As().InstancePerRequest(); builder.RegisterType().As().InstancePerRequest(); builder.RegisterType().As().InstancePerRequest(); builder.RegisterType().As().InstancePerRequest(); builder.RegisterType().As().InstancePerRequest(); builder.RegisterType().As().InstancePerRequest(); // Create our providers //builder.RegisterType().As().InstancePerLifetimeScope(); builder.RegisterType().As().InstancePerRequest(); builder.RegisterType().As().InstancePerRequest(); builder.RegisterType().As().InstancePerRequest(); builder.RegisterType().As().InstancePerRequest(); builder.RegisterType().As().InstancePerRequest(); } }
我添加了一个提供程序作为我的API构造函数的参数,如下所示:
// Readonly properties private readonly ICategoryProvider _provider; /// /// Default constructor /// public CategoriesController(ICategoryProvider provider) { _provider = provider; }
但是,当我尝试调用API(使用postman)时,我收到此错误:
{ "message": "An error has occurred.", "exceptionMessage": "An error occurred when trying to create a controller of type 'CategoriesController'. Make sure that the controller has a parameterless public constructor.", "exceptionType": "System.InvalidOperationException", "stackTrace": " at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()", "innerException": { "message": "An error has occurred.", "exceptionMessage": "Type 'Piiick.Api.Controllers.CategoriesController' does not have a default constructor", "exceptionType": "System.ArgumentException", "stackTrace": " at System.Linq.Expressions.Expression.New(Type type)\r\n at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)\r\n at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)\r\n at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)" } }
我现在卡住了,我看不出问题究竟在哪里。 类别提供者有一个这样的构造函数:
/// /// Default constructor /// public CategoryProvider(IUnitOfWork unitOfWork, ICategoryService service) { // Map our properties _unitOfWork = unitOfWork; _service = service; }
而CategoryService有一个像这样的构造函数:
/// /// The default constructor /// /// public CategoryService(IUnitOfWork unitOfWork) : base(unitOfWork) { }
最后, UnitOfWork有一个像这样的构造函数:
/// /// Default constructor /// /// The database context public UnitOfWork(DbContext context) { _context = context; _repositories = new Dictionary(); }
据我所知,一切都正确设置。 任何人都可以发现我忘记做的事吗?
我发现了这个问题,我使用HttpConfiguration
来设置依赖项解析器,它应该是GlobalConfiguration.Configuration
。
所以当我改变我的线路时:
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
至
GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
一切都开始奏效了。
尝试在构建容器之前注册已加载到应用程序域的执行上下文中的程序集:
var assemblies = AppDomain.CurrentDomain.GetAssemblies(); builder.RegisterAssemblyModules(assemblies);
/// /// Configures Autofac DI/IoC /// /// /// private IContainer ConfigureInversionOfControl(IAppBuilder app, HttpConfiguration config) { // Create our container var builder = new ContainerBuilder(); // You can register controllers all at once using assembly scanning... builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); // Register our module builder.RegisterModule(new AutofacModule()); // [!!!] ** Register assemblies of the current domain ** var assemblies = AppDomain.CurrentDomain.GetAssemblies(); builder.RegisterAssemblyModules(assemblies); // Build var container = builder.Build(); // Lets Web API know it should locate services using the AutofacWebApiDependencyResolver config.DependencyResolver = new AutofacWebApiDependencyResolver(container); // Return our container return container; }
并且不要忘记定义:
public class AutofacModule : Module { protected override void Load(ContainerBuilder builder) { ... builder.RegisterControllers(typeof(WebApiApplication).Assembly); builder.RegisterApiControllers(typeof(WebApiApplication).Assembly); } }
- 使用Directory.Delete()和Directory.CreateDirectory()覆盖文件夹
- 将自定义查询支持的导航属性添加到ODataConventionModelBuilder
- IIS编译错误-2146232576 AspNetInitializationExceptionModule
- 如何将Autofac与WepApi 2和Owin集成?
- 如何防止单个对象属性在字符串时转换为DateTime
- 使用ASP Identity 2 POST到/ Token端点时始终收到’invalid_client’错误
- 请求在Azure AppService中排队,尽管它在线程池中有足够的线程
- Web Api 2路由问题,URL中包含特殊字符
- 在ASP.Net Web Api 2中使用PUT动词上传文件