2011-01-21 7 views
2

私はASP.NET MVCアプリケーションでNInjectを使用しています。私は、オブジェクトコンテキストの作成時にシングルトンがどのように動作しているか100%確信していません。Ninject Singletons - アプリケーションレベルまたはセッションレベルで作成されますか?

、私の質問は:

以下のコードを使用すると、ユーザー・セッションごとに1 のObjectContextがあるでしょうか アプリケーション全体のシェアで1があるでしょうか?私は各ユーザ に一度に1つのコンテキストしか持たず、 をそれぞれ持っていてもらいたいが、それぞれのユーザは独自の インスタンスを持たなければならない。

InRequestScope()私が検討すべきことは何ですか?

私はWCFサービスでも同じことをします。私はその答えが両方とも同じであると仮定します。

私のGlobal.asax:

public class MvcApplication : NinjectHttpApplication 
{ 
    public static void RegisterRoutes(RouteCollection routes) 
    { 
     routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

     routes.MapRoute(
      "Default", // Route name 
      "{controller}/{action}/{id}", // URL with parameters 
      new { controller = "Change", action = "Index", id = UrlParameter.Optional } // Parameter defaults 
     ); 
    } 

    protected override void OnApplicationStarted() 
    { 
     // Ninject Code 
     base.OnApplicationStarted(); 
     AreaRegistration.RegisterAllAreas(); 
     RegisterRoutes(RouteTable.Routes); 
    } 

    protected override IKernel CreateKernel() 
    { 
     var modules = new INinjectModule[] { new ContextModule() }; 
     return new StandardKernel(modules); 
    } 

    public class ContextModule : NinjectModule 
    { 
     public override void Load() 
     { 
      Bind<ObjectContext>().To<ChangeRoutingEntities>().InSingletonScope(); 
      Bind<IObjectContext>().To<ObjectContextAdapter>(); 
      Bind<IUnitOfWork>().To<UnitOfWork>(); 
     } 
    } 
} 

答えて

2

ISingletonScopeは、アプリケーションの広い範囲です。 InRequestScopeは現在の要求に対してのみ使用されます。

セッションスコープが必要です。このタイプのスコープを実装する方法については、http://iridescence.no/post/Session-Scoped-Bindings-With-Ninject-2.aspxを参照してください。

public static class NinjectSessionScopingExtention 
{ 
    public static void InSessionScope<T>(this IBindingInSyntax<T> parent) 
    { 
     parent.InScope(SessionScopeCallback); 
    } 

    private const string _sessionKey = "Ninject Session Scope Sync Root"; 
    private static object SessionScopeCallback(IContext context) 
    { 
     if (HttpContext.Current.Session[_sessionKey] == null) 
     { 
      HttpContext.Current.Session[_sessionKey] = new object(); 
     } 

     return HttpContext.Current.Session[_sessionKey]; 
    } 
} 
+0

ありがとうございます。私たちはMVCアプリケーションのスコープをリクエストして動きました。しかし、WCFを変更する必要があります.WCFの設定、具体的にはinstanceContextModeともっと関係していると思います...いくつかの良いWCFのサンプルの方向性? – littlechris

関連する問題