Autofac和的WebAPI - 默认的构造错误 [英] Autofac and WebAPI - Default constructor error
问题描述
我有一个web表单的项目,但现在用的WebAPI的Web服务。我想实现Autofac。我越来越:
'myController的'没有默认构造函数
据该Autofac文档我有配置正确的,但显然是有问题的。我使用Visual Studio 2010 / .NET 4,这里是我的Application_Start
私人无效的Application_Start(对象发件人,EventArgs的发送)
{
//这使得API控制器在一个单独的类库
GlobalConfiguration.Configuration.Services.Replace(typeof运算(IAssembliesResolver),新AssembliesResolver()); GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always; //为ELMAH的WebAPI
GlobalConfiguration.Configuration.Filters.Add(新ElmahHandleErrorApiAttribute()); VAR JSON = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings preserveReferencesHandling = Newtonsoft.Json preserveReferencesHandling.Objects。;
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter); VAR建设者=新ContainerBuilder(); //注册的DbContext
builder.RegisterType< MyDbContext>()
。至于< IMyDbContext>()
.InstancePerRequest(); //注册服务层
变种businessLayer = Assembly.GetExecutingAssembly();
builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())
。凡(T => t.Name.EndsWith(服务))
.AsImplementedInterfaces(); builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration); 变种容器= builder.Build();
_containerProvider =新ContainerProvider(容器); VAR webApiResolver =新AutofacWebApiDependencyResolver(容器);
GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;}
一个典型的API控制器看起来是这样的:
[授权]
公共类myController的:ApiController
{
公共IMyService语境{搞定;组; } 公共myController的(IMyService上下文)
{
this.context =背景;
} //获取API / dostuff
///<总结>
///获取所有DTOS名单
///< /总结>
///<&回报GT;< /回报>
公共IEnumerable的< MyDto>得到()
{
尝试
{
返回context.MyDtos.ToList();
}
赶上(异常前)
{
VAR消息=的String.Format({0} {1} HTTP / 1.1 {2}异常:{3},Request.Method,Request.RequestUri,则httpStatus code.MethodNotAllowed,ex.Message);
VAR的errorMessage =新System.Web.Http.HttpError(消息){{错误code,405}};
抛出新Htt$p$psponseException(ControllerContext.Request.CreateErrorResponse(HttpStatus$c$c.MethodNotAllowed,错误信息));
}
}
}
如果你有你的API控制器在不同的装配比你的Web项目,那么你需要需要告诉Autofac凡与长宁找到你的控制器:
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
要
builder.RegisterApiControllers(typeof运算(myController的).Assembly);
这将指示Autofac扫描 myController的
的组装和注册所有 ApiController
派生类型它所开创那里。
I have a webforms project, but am using WebAPI for web services. I am trying to implement Autofac. I am getting:
'MyController' does not have a default constructor
According to the Autofac documentation I have the configuration correct but obviously there is a problem. I am using Visual Studio 2010/.Net 4. Here is my Application_Start
private void Application_Start(object sender, EventArgs e)
{
//This enables api controllers in a separate class library
GlobalConfiguration.Configuration.Services.Replace(typeof(IAssembliesResolver), new AssembliesResolver());
GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
//Elmah for webapi
GlobalConfiguration.Configuration.Filters.Add(new ElmahHandleErrorApiAttribute());
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
var builder = new ContainerBuilder();
//Register DbContext
builder.RegisterType<MyDbContext>()
.As<IMyDbContext>()
.InstancePerRequest();
//Register service layer
var businessLayer = Assembly.GetExecutingAssembly();
builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())
.Where(t => t.Name.EndsWith("Service"))
.AsImplementedInterfaces();
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration);
var container = builder.Build();
_containerProvider = new ContainerProvider(container);
var webApiResolver = new AutofacWebApiDependencyResolver(container);
GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;
}
A typical api controller looks like this:
[Authorize]
public class MyController : ApiController
{
public IMyService context { get; set; }
public MyController(IMyService context)
{
this.context = context;
}
// GET api/dostuff
/// <summary>
/// Get a list of all dtos
/// </summary>
/// <returns></returns>
public IEnumerable<MyDto> Get()
{
try
{
return context.MyDtos.ToList();
}
catch (Exception ex)
{
var message = string.Format("{0} {1} HTTP/1.1 {2} Exception: {3}", Request.Method, Request.RequestUri, HttpStatusCode.MethodNotAllowed, ex.Message);
var errorMessage = new System.Web.Http.HttpError(message) { { "ErrorCode", 405 } };
throw new HttpResponseException(ControllerContext.Request.CreateErrorResponse(HttpStatusCode.MethodNotAllowed, errorMessage));
}
}
}
If you have your api controllers in a different assembly than your web project, then you need to need to tell Autofac where to find your controllers with changning:
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
To
builder.RegisterApiControllers(typeof(MyController).Assembly);
This will instruct Autofac to scan the assembly of MyController
and register all ApiController
derived types what it founds there.
这篇关于Autofac和的WebAPI - 默认的构造错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!