[英]Using Autofac with Web Api 2 and Owin
Im new to DI libraries and trying to use Autofac in a WebApi 2 project with Owin. 我是DI库的新手,并试图在Owin的WebApi 2项目中使用Autofac。 This is my Owin Startup class,
这是我的Owin Startup课程,
[assembly: OwinStartup(typeof(FMIS.SIGMA.WebApi.Startup))]
namespace FMIS.SIGMA.WebApi
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
var builder = new ContainerBuilder();
var config = new HttpConfiguration();
WebApiConfig.Register(config);
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
var container = builder.Build();
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
app.UseAutofacMiddleware(container);
app.UseAutofacWebApi(config);
app.UseWebApi(config);
ConfigureOAuth(app);
}
public void ConfigureOAuth(IAppBuilder app)
{
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new SimpleAuthorizationServerProvider()
};
// Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
}
}
When I call a Api method I get this error 当我调用Api方法时,出现此错误
An error occurred when trying to create a controller of type 'MyController'.
尝试创建“ MyController”类型的控制器时发生错误。 Make sure that the controller has a parameterless public constructor.
确保控制器具有无参数的公共构造函数。
What am I missing here? 我在这里想念什么?
MyController code is something like this MyController代码是这样的
public class MyController : ApiController
{
ISomeCommandHandler someCommanHandler;
public MyController(ISomeCommandHandler SomeCommandHandler)
{
this.someCommanHandler = SomeCommandHandler;
}
// POST: api/My
public void Post([FromBody]string value)
{
someCommanHandler.Execute(new MyCommand() {
Name = "some value"
});
}
// GET: api/My
public IEnumerable<string> Get()
{
}
// GET: api/My/5
public string Get(int id)
{
}
}
You have set DependencyResolver
to AutofacWebApiDependencyResolver
, so Autofac comes into play and instantiates dependencies for you. 您已经将
DependencyResolver
设置为AutofacWebApiDependencyResolver
,因此Autofac可以发挥作用并为您实例化依赖项。 Now you have to explicitly tell Autofac which concrete implementations should be used when an instance of interface is required. 现在,您必须明确告诉Autofac当需要接口的实例时应使用哪些具体实现。
Your controller requires an instance of ISomeCommandHandler
: 您的控制器需要一个
ISomeCommandHandler
实例:
MyController(ISomeCommandHandler SomeCommandHandler)
So you need to configure types that expose that interface: 因此,您需要配置公开该接口的类型:
builder.RegisterType<CommandHandler>.As<ISomeCommandHandler>();
Have a look at this documentation section for more examples about Autofac registration concepts. 请参阅本文档部分,以获取有关Autofac注册概念的更多示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.