これは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);
}
以下のよう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
あなたのコントローラに空のコンストラクタを追加することはできません理由はありますか? –
@NikolaiSamteladze私は既に空のコンストラクタに依存性注入を実装しています。この場合はDIコンテナの使い方を知りたいだけです –
[プロジェクトがあります](https://github.com/DotNetDoodle/DotNetDoodle.Owin.Dependencies)このサポートが提供されていますが、autofacのためだけに実装されているため、ninjectのアダプタを自分で作成する必要があります。 –