【发布时间】:2018-01-15 01:14:59
【问题描述】:
我想要一个使用依赖注入 (ninject) 的单例类在应用程序启动后立即启动。单例类驻留在领域层(类库) - 领域.具体.操作。我在 WebUI 层(MVC)中使用这个类。 我被困在我计划在 Application_Start 方法中启动的服务的静态构造函数中初始化依赖项。正确的做法是什么?
单例类:
namespace Domain.Concrete.Operations
{
public sealed class SingletonClass
{
private IInterface1 _iInterface1;
private IInterface2 _iInterface2;
public SingletonClass(IInterface1 iInterface1, IInterface2 iInterface2)
{
this._iInterface1 = iInterface1;
this._iInterface2 = iInterface2;
StartAllOperations();
}
public void StartAllOperations()
{
}
}
}
NinjectDependencyResolver:
namespace WebUI.Infrastructure
{
public class NinjectDependencyResolver : IDependencyResolver
{
IKernel kernel;
public NinjectDependencyResolver(IKernel kernelParam)
{
kernel = kernelParam;
AddBindings();
}
public object GetService(Type serviceType)
{
return kernel.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return kernel.GetAll(serviceType);
}
private void AddBindings()
{
kernel.Bind<IInterface1>().To<Class1>();
kernel.Bind<IInterface2>().To<Class2>();
kernel.Bind<SingletonClass>().To<SingletonClass>().InSingletonScope();
}
}
}
据我了解,此代码将有助于返回 SigletonClass 的相同实例:
kernel.Bind<SingletonClass>().To<SingletonClass>().InSingletonScope();
App_Start 中的服务:
namespace WebUI.App_Start
{
public class OperationManagerService
{
private IInterface1 _iInterface1;
private IInterface2 _iInterface2;
static OperationManagerService() //static constructor cannot have parameters
{
_iInterface1 = //how to initialize
_iInterface2 = //interfaces here?
}
public static void RegisterService()
{
new SingletonClass(_iInterface1, _iInterface2);
}
}
}
在 Application_Start (Global.asax.cs) 中注册服务:
namespace WebUI
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
OperationManagerService.RegisterService();
}
}
}
更新:
我必须承认我能够像这样初始化依赖项,但是我只能在控制器中使用 OperationManagerService 类。 不在 Application_Start 中!
static OperationManagerService(IInterface1 iInterface1, IInterface2 iInterface2)
{
_iInterface1 = iInterface1;
_iInterface2 = iInterface2;
}
这让我想到我不能在 Application_Start 中使用 Ninject 注入。如果是真的,那么在哪里创建一个应该在启动时加载的类?
【问题讨论】:
标签: c# dependency-injection ninject