使用Autofac与Web Api 2和Owin

时间:2015-02-09 08:30:04

标签: c# dependency-injection autofac asp.net-web-api2 owin

我是DI库的新手,并尝试在Owin的WebApi 2项目中使用Autofac。这是我的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());

        }

    }
}

当我调用Api方法时,我收到此错误

  

尝试创建类型的控制器时发生错误   'myController的'。确保控制器有一个   无参数公共构造函数。

我在这里缺少什么?


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)
        {

        }
    }

1 个答案:

答案 0 :(得分:3)

您已将DependencyResolver设置为AutofacWebApiDependencyResolver,因此Autofac会发挥作用并为您实例化依赖项。现在,您必须明确告诉Autofac在需要接口实例时应该使用哪些具体实现。

您的控制器需要ISomeCommandHandler的实例:

MyController(ISomeCommandHandler SomeCommandHandler)

因此,您需要配置公开该接口的类型:

builder.RegisterType<CommandHandler>.As<ISomeCommandHandler>();

有关Autofac注册概念的更多示例,请查看此documentation section