2015-02-09 76 views
0

我是DI庫的新手,並嘗試在Owin的WebApi 2項目中使用Autofac。這是我的Owin啓動類,將Autofac與Web Api 2和Owin一起使用

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

     } 
    } 
+0

你能顯示你的MyController代碼嗎? – hugoterelle 2015-02-09 14:54:26

+0

@hugo添加了MyController代碼 – Nalaka526 2015-02-09 15:20:01

回答

3

您已設置DependencyResolverAutofacWebApiDependencyResolver,所以Autofac進場和實例依賴你。現在,您必須明確告訴Autofac在需要接口實例時應使用哪些具體實現。

你的控制器需要的ISomeCommandHandler一個實例:

MyController(ISomeCommandHandler SomeCommandHandler) 

所以,你需要配置公開該接口類型:

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

看一看這個documentation section約Autofac登記概念更多的例子。