2012-03-14 92 views
2

如果我有兩個控制器:通過多個控制器共享數據。 ASP.NET MVC

public class PrimaryController : Controller 
{ 
    private IRepository<Primaries> repository; 

    public PrimaryController(IRepository<Primaries> repository) 
    { 
     this.repository = repository; 
    } 

    // CRUD operations 
} 

public class AuxiliaryController : Controller 
{ 
    private IRepository<Primaries> repository; 

    public AuxiliaryController(IRepository<Primaries> repository) 
    { 
     this.repository = repository; 
    } 

    // CRUD operations 
    public ActionResult CreateSomethingAuxiliary(Guid id, AuxiliaryThing auxiliary) 
    { 
     var a = repository.Get(id); 
     a.Auxiliaries.Add(auxiliary); 
     repository.Save(a); 

     return RedirectToAction("Details", "Primary", new { id = id }); 
    } 
} 

DI被實施等(代碼是從Ninject模塊)

this.Bind<ISessionFactory>() 
    .ToMethod(c => new Configuration().Configure().BuildSessionFactory()) 
    .InSingletonScope(); 

this.Bind<ISession>() 
    .ToMethod(ctx => ctx.Kernel.TryGet<ISessionFactory>().OpenSession()) 
    .InRequestScope(); 

this.Bind(typeof(IRepository<>)).To(typeof(Repository<>)); 

將這工作正常嗎?我的意思是將控制器使用相同的存儲庫實例?

謝謝!

回答

2

簡單的答案 - 是的!對於所有控制器,代碼將使用相同的實現,除非您明確配置,否則使用When...方法。

如果你想重用沒有實現,但同一對象的情況下,你可以配置,使用方法,如InScopeInRequestScopeInSingletonScope因爲你已經對的ISession和ISessionFactory做。

從技術文檔:

// Summary: 
//  Indicates that instances activated via the binding should be re-used within 
//  the same HTTP request. 
IBindingNamedWithOrOnSyntax<T> InRequestScope(); 


// 
// Summary: 
//  Indicates that only a single instance of the binding should be created, and 
//  then should be re-used for all subsequent requests. 
IBindingNamedWithOrOnSyntax<T> InSingletonScope(); 

在單用Repository是不是一個好主意。我使用InRequestScope使一個實例只提供一個請求。如果使用實體框架,您可以查看this answer的詳細信息

+0

是的我需要相同的實例。那麼我應該使用'InSingletonScope'嗎? – lexeme 2012-03-14 06:39:21

+0

看看更新 – archil 2012-03-14 06:50:46

1

這取決於ninject中的默認範圍如何工作(我不是ninject用戶)。

如果您在存儲庫映射指定InRequestScope它將然而工作。

this.Bind(typeof(IRepository<>)) 
    .To(typeof(Repository<>)) 
    .InRequestScope(); 

只要與數據庫的連接沒有關閉,Singleton作用域就會工作。因爲所有請求都會嘗試使用同一個存儲庫對象,所以您的應用程序會在它停止工作時停止工作。

這就是爲什麼請求範圍更好。如果回購失敗,它只會失敗的一個請求(除非它是數據庫的問題)。

我寫了一套最佳實踐:http://blog.gauffin.org/2011/09/inversion-of-control-containers-best-practices/