簡體   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