在我的MVC項目,我安裝我的MvcApplication_start():問題的理解Ninject綁定/注塑
ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
,併成功地結合了。要對我的IProductsRepository到MySqlProductsRepository:
public class NinjectControllerFactory : DefaultControllerFactory
{
private readonly IKernel _kernel = new StandardKernel(new MyServices());
protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
{
if (controllerType == null)
return null;
return (IController) _kernel.Get(controllerType);
}
public class MyServices: NinjectModule
{
public override void Load()
{
Bind<IProductsRepository>().To<MySqlProductsRepository>();
}
}
}
但我使用NHibernate,並有一個單獨的Session Factory類,它有一個返回ISession的GetSession()方法。
public static ISessionFactory SessionFactory = CreateSessionFactory();
private static ISessionFactory CreateSessionFactory()
{
var cfg = new Configuration().Configure(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "nhibernate.config"));
cfg.SetProperty(NHibernate.Cfg.Environment.ConnectionStringName, System.Environment.MachineName);
NHibernateProfiler.Initialize();
return cfg.BuildSessionFactory();
}
public static ISession GetSession()
{
return SessionFactory.GetCurrentSession();
}
我想設定,讓我MySqlProductsRepository將通過Ninject創建時獲得通過,ISession的對象:
public class MySqlProductsRepository : IProductsRepository
{
private readonly ISession _session;
public MySqlProductsRepository(ISession session)
{
_session = session;
}
我的控制器將被交到IProductsRepository實例:
public class AdminController : Controller
{
private readonly IProductsRepository _productsRepository;
public AdminController(IProductsRepository productsRepository)
{
_productsRepository = productsRepository;
}
我的問題:
我似乎無法弄清楚米y IoC容器,其中我將我的IProductsRepository綁定到我的Repository,如何註冊一個ISession,如何在創建時將一個ISession傳遞給MyProductsRepository對象,並將一個MyProductsRepository對象交給我的控制器?
+1奇妙的東西 - 填補市場空白 - 這應該成爲這類問題的常見問題解答! – 2010-11-22 01:21:40
感謝Bob,完美的,現在開始閱讀他們,應該是一個主要的幫助。 – pghtech 2010-11-22 14:21:18