3

Asp.net Web Api プロジェクトの WebApiConfig クラスで Ninject を使用してクラスのインスタンスを注入できますか? これは私の試みです

    public static class WebApiConfig
    {    
        private static IAccountsService _accountsService;

        [Inject]
        public static IAccountsService AccountsService 
        {
            get { return _accountsService; }
            set { _accountsService = value; }
        }

        public static void Register(HttpConfiguration config)
        {
            var authentication = CreateAuthenticationConfiguration();
            config.MessageHandlers.Add(new AuthenticationHandler(authentication));

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.EnableSystemDiagnosticsTracing();
        }

        private static AuthenticationConfiguration CreateAuthenticationConfiguration()
        {
            var authentication = new AuthenticationConfiguration
            {
                RequireSsl = false,
                EnableSessionToken = true
            };

            // Basic Authentication
            authentication.AddBasicAuthentication(AccountsService.ValidateAccountUsingSiteCredential);

            return authentication;
        }
    }

しかし、私はObject reference not set to an instance of an objectこの線に乗っていますauthentication.AddBasicAuthentication(AccountsService.Validate);

4

2 に答える 2

1

依存関係を挿入するために、global.asax で次のようなものを使用しています。

DependencyResolver.Current.GetService<WebApiConfig>()
     .Register(GlobalConfiguration.Configuration);

WebApiConfig編集:私たちのクラスは静的ではないことに言及するのを忘れていました。

于 2013-08-28T21:57:46.357 に答える
0

あなたを助けることができるいくつかのこと

1) 次のメソッドを実行する Ninject.Web.Common パッケージを使用します。

[アセンブリ: WebActivatorEx.PreApplicationStartMethod(typeof(NinjectWebCommon), "Start")] [アセンブリ: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(NinjectWebCommon), "Stop")]

PreApplicationStartMethod が AppStartの前に実行され、「Ninject.Web.Common」を追加すると、サービスをワイヤアップする方法についてのガイドが表示されます。

2) 私は通常、メソッド呼び出しInitialize(IKernel ninjectKernel)を持つINeedInitializationと呼ばれるインターフェイスを実装することを好みます。

このようにして、実行時にすべての実装を動的に見つけ、Ninject の StandardKernel のインスタンスを渡し、プラグ アンド プレイ方式でバインディングを実行できます。

3)すべてのモジュールがロードされた後、NinjectWebCommon から IKernal インスタンスを「KernelInstance」として公開します。

4) 以下を使用して、 「 INeedInitialization 」の実装の 1 つまたはバインディング ロジックがある場所で、「 YourMessageHandler」をそれ自体 kernel.Bind().ToSelf().InSingletonScope() にバインドできます。すべての依存関係は、コンストラクター注入を介して注入できます。

5)この config.MessageHandlers.Add(NinjectWebCommon.KernelInstance.Get< YourMessageHandler >());のような「YourMessageHandler」ハンドラーを登録します。

6) アプリケーションを起動し、NInject に魔法をかけてもらいます

于 2016-02-11T23:27:04.503 に答える