繁体   English   中英

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

[英]Using Autofac with Web Api 2 and 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)
        {

        }
    }

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

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

MyController(ISomeCommandHandler SomeCommandHandler)

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

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

请参阅本文档部分,以获取有关Autofac注册概念的更多示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM