0

显然,我错过了一些东西。我有一个 MVC 应用程序并安装了 Ninject 3 和 MVC3 扩展(尽管我正在运行 MVC4)。我有一个SiteSettings在整个项目中引用的类,如下所示:

public class SiteSettings
{
    private static readonly Common.Logging.ILog Logger = Common.Logging.LogManager.GetCurrentClassLogger();
    private static ObservableDictionary<string, string> settings;
    private static bool Initialized = false;
    private static DataPersister persister;

    public static void Initialize()
    {
        if (Initialized) throw new InvalidOperationException("The SiteSettings object has already been initialized.");
        persister = new DataPersister();
        using (var u = persister.UnitOfWorkFactory.GetUnitOfWork())
        {
            var settingsList = u.SiteSettings.GetAll();
            settings = new ObservableDictionary<string, string>(settingsList.ToDictionary(key => key.SiteSettingName, value => value.SiteSettingValue));
            settings.OnChange += new kvpChangeEvent<string, string>(settings_OnChange);
        }
        Initialized = true;
    }

    static void settings_OnChange(object sender, odKVPChangeEventArgs<string, string> e)
    {
        using (var u = persister.UnitOfWorkFactory.GetUnitOfWork())
        {
            var setting = u.SiteSettings.GetByName(e.Key);
            setting.SiteSettingValue = e.Value;
            u.SiteSettings.Update(setting);
            u.Save();
            Logger.Info(i => i("Changed the '{0}' site setting from '{1}' to '{2}'.", e.Key, e.OldValue, e.Value));
        }
    }

    private static int _ItemsPerPage;
    public static int ItemsPerPage
    {
        get
        {
            return _ItemsPerPage;
        }
        set
        {
            _ItemsPerPage = value;
            settings["itemsPerPage"] = value.ToString();
        }
    }

    private static int _SessionLifeInMinutes;
    public static int SessionLifeInMinutes
    {
        get
        {
            return _SessionLifeInMinutes;
        }
        set
        {
            _SessionLifeInMinutes = value;
            settings["sessionLifeInMinutes"] = value.ToString();
        }
    }

    private static string _DateFormat;
    public static string DateFormat
    {
        get
        {
            return _DateFormat;
        }
        set
        {
            _DateFormat = value;
            settings["defaultDateFormat"] = value;
        }
    }
}

我像这样构建了一个数据持久性对象:

public class DataPersister
{
    public IUnitOfWorkFactory UnitOfWorkFactory { get; set; }
}

...我的NinjectWebCommon.cs长相是这样的:

public static class NinjectWebCommon
{
    private static readonly Bootstrapper bootstrapper = new Bootstrapper();

    /// <summary>
    /// Starts the application
    /// </summary>
    public static void Start()
    {
        DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
        DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
        bootstrapper.Initialize(CreateKernel);
    }

    /// <summary>
    /// Stops the application.
    /// </summary>
    public static void Stop()
    {
        bootstrapper.ShutDown();
    }

    /// <summary>
    /// Creates the kernel that will manage your application.
    /// </summary>
    /// <returns>The created kernel.</returns>
    private static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
        kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

        RegisterServices(kernel);
        return kernel;
    }

    /// <summary>
    /// Load your modules or register your services here!
    /// </summary>
    /// <param name="kernel">The kernel.</param>
    private static void RegisterServices(IKernel kernel)
    {
        kernel.Bind<IUnitOfWork>().To<NHUnitOfWork>();
        kernel.Bind<IUnitOfWorkFactory>().To<NHUnitOfWorkFactory>();
    }
}

在我看来,我已经满足了依赖注入的所有要求。我的Global.asax.cs Application_Start()样子是这样的:

protected void Application_Start()
{
    ViewEngines.Engines.Clear();
    ViewEngines.Engines.Add(new MonoRazorViewEngine());

    AreaRegistration.RegisterAllAreas();
    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
    ControllerBuilder.Current.DefaultNamespaces.Add("MyApplication.Application.Controllers");
    Initialize.Security();
    SiteSettings.Initialize();
}

...然而,当我尝试收集我需要的数据时,我的SiteSettings班级总是有一个空值。IUnitOfWorkFactory

我究竟做错了什么?一切似乎都像所有例子所暗示的那样,但我没有得到爱。

更新

使用 Bassam Mehanni 的建议,我将我的DataPersister课程改写为如下所示:

public class DataPersister
{
    private IUnitOfWorkFactory UnitOfWorkFactory;
    public DataPersister(IUnitOfWorkFactory unitOfWorkFactory)
    {
        UnitOfWorkFactory = unitOfWorkFactory;
    }
    public IUnitOfWork GetUnitOfWork()
    {
        return UnitOfWorkFactory.GetUnitOfWork();
    }
}

...但当然现在我的SiteSettings班级抱怨我的无参数构造函数。我该怎么办?

更新 2

好的,继续,我DataPersister像这样重写了我的课程:

public class DataPersister
{
    private static readonly Common.Logging.ILog Logger = Common.Logging.LogManager.GetCurrentClassLogger();

    private IUnitOfWorkFactory UnitOfWorkFactory { get; set; }
    public IUnitOfWork GetUnitOfWork()
    {
        return UnitOfWorkFactory.GetUnitOfWork();
    }
    [Inject]
    public DataPersister(IUnitOfWorkFactory factory)
    {
        Logger.Info("Injected constructor called");
        UnitOfWorkFactory = factory;
    }
    public DataPersister()
    {
        Logger.Info("Parameterless constructor called");
    }
}

然后我SiteSettings像这样重写了我的课程:

public class SiteSettings
{
    private static readonly Common.Logging.ILog Logger = Common.Logging.LogManager.GetCurrentClassLogger();
    private ObservableDictionary<string, string> settings;
    private DataPersister persister;
    private SiteSettings()
    {
        persister = new DataPersister();
        using (var u = persister.GetUnitOfWork())
        {
            var settingsList = u.SiteSettings.GetAll();
            settings = new ObservableDictionary<string, string>(settingsList.ToDictionary(key => key.SiteSettingName, value => value.SiteSettingValue));
            settings.OnChange += new kvpChangeEvent<string, string>(settings_OnChange);
        }
    }
    private static SiteSettings instance;

    public static SiteSettings Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new SiteSettings();
            }
            return instance;
        }
    }

    private void settings_OnChange(object sender, odKVPChangeEventArgs<string, string> e)
    {
        using (var u = persister.GetUnitOfWork())
        {
            var setting = u.SiteSettings.GetByName(e.Key);
            setting.SiteSettingValue = e.Value;
            u.SiteSettings.Update(setting);
            u.Save();
            Logger.Info(i => i("Changed the '{0}' site setting from '{1}' to '{2}'.", e.Key, e.OldValue, e.Value));
        }
    }

    private int _ItemsPerPage;
    public int ItemsPerPage
    {
        get
        {
            return _ItemsPerPage;
        }
        set
        {
            _ItemsPerPage = value;
            settings["itemsPerPage"] = value.ToString();
        }
    }

    private int _SessionLifeInMinutes;
    public int SessionLifeInMinutes
    {
        get
        {
            return _SessionLifeInMinutes;
        }
        set
        {
            _SessionLifeInMinutes = value;
            settings["sessionLifeInMinutes"] = value.ToString();
        }
    }

    private string _DateFormat;
    public string DateFormat
    {
        get
        {
            return _DateFormat;
        }
        set
        {
            _DateFormat = value;
            settings["defaultDateFormat"] = value;
        }
    }
}

这不应该工作吗?因为它没有。该类DataPersister始终使用无参数构造函数调用。我的内核绑定如下所示:

private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<IUnitOfWork>().To<NHUnitOfWork>();
    kernel.Bind<IUnitOfWorkFactory>().To<NHUnitOfWorkFactory>();
}

还有什么我想念的吗?这变得非常令人沮丧。

4

2 回答 2

3

通常 ninject 会在构造函数或其他东西中注入您的服务,它不会在运行时神奇地将所有接口转换为对象实例

例如:

public class MyController : Controller
{
   private IServiceThatINeed _serviceThatINeed;
   public MyController(IServiceThatINeed serviceThatINeed)
   { 
       _serviceThatINeed = _serviceThatINeed;
   }
}

在这种情况下,由于您注册了内核实例,mvc 知道如何解决这种依赖关系,并将传递一个实现的对象的实例IServiceThatINeed(假设您告诉 ninject 如何解决这种依赖关系。

现在可能会有一个实例,您需要在不通过 mvc 框架将其注入构造函数的情况下获取服务,在这些实例中(就像您在此处所拥有的实例一样),您将需要使用ServiceLocator

例如:

var myService = ServiceLocator.Current.GetInstance<IServiceThatINeed>()

要使用ServiceLocator,您需要添加对Microsoft.Practices.ServiceLocation

希望有帮助!

于 2013-01-17T23:45:37.410 回答
3

在使用 IoC 容器时,不应该依赖非静态类的静态类。相反,您应该创建一个具有单例生命周期的非静态类。

  1. 使您的 SiteSettings 类不是静态的。
  2. 使用构造函数注入将所有依赖项(例如 IUnitOfWorkFactory)注入 SiteSettings
  3. 在单例范围内为 SiteSettings 创建绑定
  4. 在需要访问 unsing 构造函数注入的任何地方获取 SiteSettings 的实例。

例子:

public class SiteSettings {
    public SiteSettings(IUnitOfWorkFactory uowFactory) { .... }

    ....
}


public class INeedToAccessSiteSettings
{
    public INeedToAccessSiteSettings(SiteSettings siteSettings) { .... }
}

kenrel.Bind<SiteSettings>().ToSelf().InSingletonScope();
于 2013-01-18T11:56:44.770 回答