将 Autofac 与 Web Api 2 和 Owin 结合使用

Using Autofac with Web Api 2 and Owin

我是 DI 库的新手,正在尝试在 Owin 的 WebApi 2 项目中使用 Autofac。这是我的 Owin Startup class,

[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 方法时出现此错误

An error occurred when trying to create a controller of type 'MyController'. Make sure that the controller has a parameterless public constructor.

我在这里错过了什么?


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

        }
    }

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

您的控制器需要 ISomeCommandHandler:

的实例
MyController(ISomeCommandHandler SomeCommandHandler)

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

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

查看此 documentation section 以获取有关 Autofac 注册概念的更多示例。