2016-10-20 3 views
1

完全にシングルトンアプリケーション(WebとConsole)を作成しようとしています。 しかし、Entity DbContextはWeb上でPerWebRequestを使用する必要があります。すべてのクラスのDryIoc WebRequestとしてのSingletonとDbContext

これをサポートするには、コンテナにどのように登録する必要がありますか? クラスがシングルトンとして初期化されると、私はシングルトンとしてすべての注入されたクラスを持つメモリ上の単一のインスタンスで実行されることを理解します。

次のコードは、すべてのWebアプリケーションとコンソールアプリケーションのContainer Initializationです。 - コンソールで実行しているときにどのように登録すればよいですか? - Web上で動作し、Owinがスタートアップを呼び出すとき、認証で使用するオブジェクトを解決する必要があることがありますが、Owinは「コンテキストなし」環境で動作します。どのようにそれを検出し、使用する?

private static IContainer Initialize(IContainer container) 
    { 
     if (container == null) 
      container = new Container(
       rules => rules 
        .WithDefaultReuseInsteadOfTransient(Reuse.InWebRequest) 
        .WithFactorySelector(Rules.SelectLastRegisteredFactory()) 
        .With(FactoryMethod.ConstructorWithResolvableArguments) 
        .WithoutThrowOnRegisteringDisposableTransient(), 
       scopeContext: new AsyncExecutionFlowScopeContext() 
      ); 

     string prefix = GetPrefix(); 

     var implementingClasses = 
      AppDomain.CurrentDomain.GetAssemblies().ToList() 
       .Where(x => x.FullName.StartsWith(prefix)) 
       .SelectMany(x => x.GetTypes()) 
       .Where(type => 
        (type.Namespace != null && type.Namespace.StartsWith(prefix)) && 
        type.IsPublic &&     // get public types 
        !type.IsAbstract &&     // which are not interfaces nor abstract 
        type.GetInterfaces().Length != 0); // which implementing some interface(s) 

     Parallel.ForEach(implementingClasses, implementingClass => 
     { 
      container.RegisterMany(new[] { implementingClass }, Reuse.Singleton, serviceTypeCondition: type => type.IsInterface); 
     }); 

     return container; 
    } 

答えて

0

あなたは周囲のスコープのコンテキストを使用しているとして、あなたは/あなたのシングルトンでFunc<DbContext>としてDbContextを注入消費することができます。 Funcが呼び出されるたびに、現在の環境スコープ/要求にバインドされた値が返されます。

+0

このサンプルのような汎用登録メソッドを作成する方法の例がありますか? 'パブリック静的いるIContainer RegisterWebRequest (このいるIContainer容器、){ container.Register 、のFunc >(リユース:Reuse.InWebRequest、製:Made.Of(()=>新しいT())、ifAlreadyRegistered。 IfAlreadyRegistered.Replace); リターンコンテナ。 ' – lcmassena

+0

最後のコメントは無視してください。あなたのbitbucketで問題を作りました:https://bitbucket.org/dadhi/dryioc/issues/378/resolve-a-single-instance-inwebrequest – lcmassena

関連する問題