2013-11-05 9 views
58

これはWeb API 2プロジェクトです。私はNinjectを使用してDIを実装する場合OwinStartupのときのDIコンテナの使い方

、私はタイプのコントローラを作成しようとしたときにエラーが発生したエラーメッセージ

を得た「TokenController」。コントローラにパラメータのないパブリックコンストラクタがあることを確認します。

[assembly: OwinStartup(typeof(Web.Startup))] 

namespace Web 
{ 
    public partial class Startup 
    { 
     public void Configuration(IAppBuilder app) 
     { 
      ConfigureAuth(app); 
      ConfigureWebApi(app); 
     } 
    } 
} 

public class TokenController : ApiController 
{ 

    private IUserService _userService; 

    public TokenController(IUserService userService) 
    { 
     this._userService = userService; 
    } 

    [Route("api/Token")] 
    public HttpResponseMessage PostToken(UserViewModel model) 
    { 
     if (_userService.ValidateUser(model.Account, model.Password)) 
     { 
      ClaimsIdentity identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType); 
      identity.AddClaim(new Claim(ClaimTypes.Name, model.Account)); 
      AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties()); 
      var currentUtc = new SystemClock().UtcNow; 
      ticket.Properties.IssuedUtc = currentUtc; 
      ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30)); 
      return new HttpResponseMessage(HttpStatusCode.OK) 
      { 
       Content = new ObjectContent<object>(new 
       { 
        UserName = model.Account, 
        AccessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket) 
       }, Configuration.Formatters.JsonFormatter) 
      }; 
     } 

     return new HttpResponseMessage(HttpStatusCode.BadRequest); 
    } 
} 

私は

Ninject正常に動作してweb.configする<add key="owin:AutomaticAppStartup" value="false" />を追加すると、 しかしStartup.OAuthBearerOptions.AccessTokenFormatがOWINでDIコンテナを使用する方法

をnullになりましたか?

UPDATE

IDependencyResolverを実装し、単純なインジェクタ場合

public void ConfigureWebApi(IAppBuilder app) 
{ 
    HttpConfiguration config = new HttpConfiguration(); 

    config.DependencyResolver = new NinjectDependencyResolver(NinjectWebCommon.CreateKernel()); 

    app.UseWebApi(config); 
} 

NinjectDependencyResolver


以下のようWebAPIの依存リゾルバを使用

public void ConfigureWebApi(IAppBuilder app) 
{ 
    HttpConfiguration config = new HttpConfiguration(); 

    var container = new Container(); 
    container.Register<IUserService, UserService>(); 
    config.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container); 

    app.UseWebApi(config); 
} 

SimpleInjectorWebApiDependencyResolver

+0

あなたのコントローラに空のコンストラクタを追加することはできません理由はありますか? –

+0

@NikolaiSamteladze私は既に空のコンストラクタに依存性注入を実装しています。この場合はDIコンテナの使い方を知りたいだけです –

+0

[プロジェクトがあります](https://github.com/DotNetDoodle/DotNetDoodle.Owin.Dependencies)このサポートが提供されていますが、autofacのためだけに実装されているため、ninjectのアダプタを自分で作成する必要があります。 –

答えて

32

あなたはthis blog postを見てみたいことがあります。

Unityを使用していますが、最終的には同じにする必要があります。

基本的に、WebAPI依存関係リゾルバを使用してください。すべてが正しくマップされていることを確認してください。

DIを設定した後もOAuthトークンに問題がある場合は、教えてください。

乾杯

+0

私はWebAPI Dependency Resolverを使用しています。 –

2

私たちは、その後、我々はそうのように私たちのバインディングを構成nuget

PM>インストール・パッケージをninject.MVC5

でインストール標準ninject.MVC5パッケージを使用します。

kernel.Bind<IDbContext, DbContext>() 
    .To<BlogContext>() 
    .InRequestScope(); 

kernel.Bind<IUserStore<User>>() 
    .To<UserStore<User>>() 
    .InRequestScope(); 

kernel.Bind<IDataProtectionProvider>() 
    .To<DpapiDataProtectionProvider>() 
    .InRequestScope() 
    .WithConstructorArgument("ApplicationName"); 

kernel.Bind<ApplicationUserManager>().ToSelf().InRequestScope() 
    .WithPropertyValue("UserTokenProvider", 
     new DataProtectorTokenProvider<User>(
      kernel.Get<IDataProtectionProvider>().Create("EmailConfirmation") 
      )); 

ユーザーモデルをどれだけカスタマイズしたかによって調整が必要な場合があります。例えば、ユーザストアのバインディングは、次のようなものかもしれません。

kernel.Bind<IUserStore<User, int>>() 
     .To<IntUserStore>().InRequestScope(); 

また、必要なユーザーマネージャの設定は、パスワードポリシーをユーザーマネージャコンストラクタで設定することもできます。

これは以前のサンプルのcreateメソッドにありましたが、これはもう必要ありません。 また、ninjectがあなたのために解決を処理するように、コンテキストコールを取得するowinを取り除くことができます。

+0

内部的には、アイデンティティの一部がOWINに依存している(つまり、OwinContext.Get()を呼び出す)というチャッターがあります。あなたはこれに関連して奇妙なことや問題を見たことがありますか? – JasonCoder

+0

@JasonCoderいいえ、問題が発生したとは言えません。 – jps

17

更新

これは、よりまっすぐ進む今Ninject.Web.WebApi.OwinHost Nugetパッケージのおかげである:

Startup.cs

using Ninject; 
using Ninject.Web.Common.OwinHost; 
using Ninject.Web.WebApi.OwinHost; 
using Owin; 
using System.Web.Http; 

namespace Xxx 
{ 
    public class Startup 
    { 
     public void Configuration(IAppBuilder app) 
     { 
      var config = new HttpConfiguration(); 
      config.MapHttpAttributeRoutes(); 
      config.Routes.MapHttpRoute("DefaultApi", "myservice/{controller}/{id}", new { id = RouteParameter.Optional }); 

      app.UseNinjectMiddleware(CreateKernel); 
      app.UseNinjectWebApi(config); 
     } 
    } 
    public static IKernel CreateKernel() 
    { 
     var kernel = new StandardKernel(); 

     kernel.Bind<IMyService>().To<MyService>(); 
     return kernel; 
    } 
} 

私はそれに応じてWikiを更新しました。

https://github.com/ninject/Ninject.Web.Common/wiki/Setting-up-a-OWIN-WebApi-application

すべての3つのホスティングオプション。

https://github.com/ninject/Ninject.Web.WebApi/wiki/Setting-up-an-mvc-webapi-application

+1

私は非常にシンプルなexample owinのホストされたアプリケーションのためにこれを試しています、そして、それは最初の呼び出しのためだけに働きます。その後の呼び出しでエラーが発生します: "コントローラにパラメータのないパブリックコンストラクタがあることを確認してください。"なぜどんなアイデア? –

関連する問題