在共享视图中使用 ninject 绑定接口
Bind an interface using ninject in shared view
我使用 ninject 将我的接口绑定到我的存储库,如您所见:
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<CMSDataContext>().To<CMSDataContext>().InRequestScope();
kernel.Bind<IUserRepository>().To<UserRepository>().InRequestScope();
kernel.Bind<INewsRepository>().To<NewsRepository>().InRequestScope();
kernel.Bind<IConfigurationRepository>().To<ConfigurationRepository>().InRequestScope();
}
例如你可以在这里看到 home controller
的结构:
public class HomeController : Controller
{
//
// GET: /fa/Home/
private IConfigurationRepository _configurationRepository;
public HomeController(IConfigurationRepository configurationRepository)
{
_configurationRepository = configurationRepository;
}
public ActionResult Index()
{
ViewBag.Configuration = _configurationRepository.GetConfiguration().First();
return View();
}
}
但是我需要在我的 shared view
中调用一个接口,我的意思是 masterpage
正如你在这里看到的那样:
<head>
@{
IConfigurationRepository _iconfigurationRepository;
}
<!-- Basic -->
<title>@ViewBag.Configuration.Title</title>
<!-- Define Charset -->
<meta charset="utf-8" />
我的问题是如何将此界面绑定到其存储库,我的意思是 configurationRepository
使用 ninject?
如果您需要在视图中解析依赖项,可以使用 dependencyResolver。
在您的剃刀视图中:
@{
var config = DependencyResolver.Current.GetService<IConfigurationRepository >();
}
在这种情况下,如果 ninject 可以解析构造函数参数,那么 ninject 是当前的依赖解析器,您可以在视图、过滤器、控制器等中使用
我使用 ninject 将我的接口绑定到我的存储库,如您所见:
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<CMSDataContext>().To<CMSDataContext>().InRequestScope();
kernel.Bind<IUserRepository>().To<UserRepository>().InRequestScope();
kernel.Bind<INewsRepository>().To<NewsRepository>().InRequestScope();
kernel.Bind<IConfigurationRepository>().To<ConfigurationRepository>().InRequestScope();
}
例如你可以在这里看到 home controller
的结构:
public class HomeController : Controller
{
//
// GET: /fa/Home/
private IConfigurationRepository _configurationRepository;
public HomeController(IConfigurationRepository configurationRepository)
{
_configurationRepository = configurationRepository;
}
public ActionResult Index()
{
ViewBag.Configuration = _configurationRepository.GetConfiguration().First();
return View();
}
}
但是我需要在我的 shared view
中调用一个接口,我的意思是 masterpage
正如你在这里看到的那样:
<head>
@{
IConfigurationRepository _iconfigurationRepository;
}
<!-- Basic -->
<title>@ViewBag.Configuration.Title</title>
<!-- Define Charset -->
<meta charset="utf-8" />
我的问题是如何将此界面绑定到其存储库,我的意思是 configurationRepository
使用 ninject?
如果您需要在视图中解析依赖项,可以使用 dependencyResolver。
在您的剃刀视图中:
@{
var config = DependencyResolver.Current.GetService<IConfigurationRepository >();
}
在这种情况下,如果 ninject 可以解析构造函数参数,那么 ninject 是当前的依赖解析器,您可以在视图、过滤器、控制器等中使用