我正在尝试在我的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);
}
/// <summary>
/// Configures Autofac DI/IoC
/// </summary>
/// <param name="app"></param>
/// <param name="config"></param>
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<DatabaseContext>().As<DbContext>().InstancePerRequest();
// Create our Services
builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerRequest();
builder.RegisterType<AnswerService>().As<IAnswerService>().InstancePerRequest();
builder.RegisterType<CategoryService>().As<ICategoryService>().InstancePerRequest();
builder.RegisterType<FeedService>().As<IFeedService>().InstancePerRequest();
builder.RegisterType<FilterService>().As<IFilterService>().InstancePerRequest();
builder.RegisterType<QuestionGroupService>().As<IQuestionGroupService>().InstancePerRequest();
builder.RegisterType<StateService>().As<IStateService>().InstancePerRequest();
// Create our providers
//builder.RegisterType<AnswerProvider>().As<IAnswerProvider>().InstancePerLifetimeScope();
builder.RegisterType<CategoryProvider>().As<ICategoryProvider>().InstancePerRequest();
builder.RegisterType<FeedProvider>().As<IFeedProvider>().InstancePerRequest();
builder.RegisterType<FilterProvider>().As<IFilterProvider>().InstancePerRequest();
builder.RegisterType<QuestionGroupProvider>().As<IQuestionGroupProvider>().InstancePerRequest();
builder.RegisterType<StateProvider>().As<IStateProvider>().InstancePerRequest();
}
}
我添加了一个提供程序作为我的API构造函数的参数,如下所示:
// Readonly properties
private readonly ICategoryProvider _provider;
/// <summary>
/// Default constructor
/// </summary>
public CategoriesController(ICategoryProvider provider)
{
_provider = provider;
}
但是,当我尝试调用API(使用邮递员)时,我收到此错误:
{
"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.<SendAsync>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)"
}
}
我现在卡住了,我看不出问题究竟在哪里。 类别提供者有一个像这样的构造函数:
/// <summary>
/// Default constructor
/// </summary>
public CategoryProvider(IUnitOfWork unitOfWork, ICategoryService service)
{
// Map our properties
_unitOfWork = unitOfWork;
_service = service;
}
并且 CategoryService 有一个像这样的构造函数:
/// <summary>
/// The default constructor
/// </summary>
/// <param name="unitOfWork"></param>
public CategoryService(IUnitOfWork unitOfWork)
: base(unitOfWork)
{
}
最后, UnitOfWork 有一个像这样的构造函数:
/// <summary>
/// Default constructor
/// </summary>
/// <param name="context">The database context</param>
public UnitOfWork(DbContext context)
{
_context = context;
_repositories = new Dictionary<Type, object>();
}
据我所知,一切都设置正确。 任何人都可以发现我忘记做的事吗?
答案 0 :(得分:4)
我发现了这个问题,我使用HttpConfiguration
来设置依赖项解析器,它应该是GlobalConfiguration.Configuration
。
所以当我改变我的行时:
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
到
GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
一切都开始了。
答案 1 :(得分:0)
尝试在构建容器之前注册已加载到应用程序域的执行上下文中的程序集:
var assemblies = AppDomain.CurrentDomain.GetAssemblies(); builder.RegisterAssemblyModules(assemblies);
/// <summary>
/// Configures Autofac DI/IoC
/// </summary>
/// <param name="app"></param>
/// <param name="config"></param>
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);
}
}