2016-11-17 7 views
2

私はASP.NET Coreを使用しており、実行時にIServiceProviderにサービスを追加したいので、DI経由でアプリケーション全体で使用できます。DI経由でランタイムにサービスを登録しますか?

たとえば、ユーザーは設定コントローラにアクセスし、認証設定を「オン」から「オフ」に変更することがあります。そのインスタンスでは、実行時に登録されたサービスを置き換えたいと思います。設定コントローラで

擬コード:

if(settings.Authentication == false) 
{ 
    services.Remove(ServiceDescriptor.Transient<IAuthenticationService, AuthenticationService>()); 
    services.Add(ServiceDescriptor.Transient<IAuthenticationService, NoAuthService>()); 
} 
else 
{ 
    services.Remove(ServiceDescriptor.Transient<IAuthenticationService, NoAuthService> 
    services.Add(ServiceDescriptor.Transient<IAuthenticationService, AuthenticationService>()); 
} 

IServiceCollectionがIServiceProviderに内蔵されていなかったので、私は私のStartup.csでそれをやっているときに、このロジックは正常に動作します。しかし、Startupが既に実行された後でこれを実行できるようにしたい。これが可能なのか誰にも分かりますか?

答えて

5

実行時にサービスを登録/削除する代わりに、実行時に適切なサービスを決定するサービスファクトリを作成します。クラスの

services.AddTransient<AuthenticationService>(); 
services.AddTransient<NoAuthService>(); 
services.AddTransient<IAuthenticationServiceFactory, AuthenticationServiceFactory>(); 

AuthenticationServiceFactory.cs

public class AuthenticationServiceFactory: IAuthenticationServiceFactory 
{ 
    private readonly AuthenticationService _authenticationService; 
    private readonly NoAuthService_noAuthService; 
    public AuthenticationServiceFactory(AuthenticationService authenticationService, NoAuthService noAuthService) 
    { 
     _noAuthService = noAuthService; 
     _authenticationService = authenticationService; 
    } 
    public IAuthenticationService GetAuthenticationService() 
    { 
      if(settings.Authentication == false) 
      { 
      return _noAuthService; 
      } 
      else 
      { 
       return _authenticationService; 
      } 
    } 
} 

使用法:

public class SomeClass 
{ 
    public SomeClass(IAuthenticationServiceFactory _authenticationServiceFactory) 
    { 
     var authenticationService = _authenticationServiceFactory.GetAuthenticationService(); 
    } 
} 
+0

うん、それは正しいアプローチです! –

+2

@Dawidあなたはこれが「正しいアプローチ」だとどのような権限で言いますか?あなたは_「これもそうだろう」という意味ですか?どうして?なぜそれは良い答えですか? – CodeCaster

+0

Design Patternsの観点からは、いくつかの詳細を隠すファクトリ(この場合はいくつかの設定/設定を取得する)を登録して、適切な実装を提供するほうがよいからです。 –

関連する問題