我正在寻找一种将设置合并到我的网络应用程序 (asp mvc) 中的好方法。我在 NopCommerce 中遇到了一个非常好的实现。 NopCommerce 使用名称和值将值存储在数据库表中。该名称派生自类和属性名称(例如 customersettings.settingname1)
NopCommerce 使用设置的确切方式可以在这个问题中找到:Understanding how Nop Commerce settings are loaded from the database
NopCommerce 使用 Autofac 作为 DI 框架将 Settings
绑定(bind)到 ConfigurationProvider
如下(我是对的)。
return RegistrationBuilder
.ForDelegate((c, p) => c.Resolve<IConfigurationProvider<TSettings>>().Settings)
.InstancePerHttpRequest()
.CreateRegistration();
在适当的类中,您现在可以使用 ClientSettings
作为参数,它会自动填充数据库中的数据。
我真的很喜欢这个实现,因为它非常灵活。然而,问题是我正在使用 Ninject。我已经尝试了几种方法来获得正确的绑定(bind),但似乎无法找到正确的实现。有谁知道如何让它工作?
编辑:
我找到了一种直接绑定(bind) ClientSettings
的方法:
kernel.Bind<ClientSettings>()
.ToMethod(ctx => ctx.Kernel.Get<IConfigurationProvider<ClientSettings>>().Settings)
.InRequestScope();
但是有什么办法可以做到这一点吗?
kernel.Bind<ISettings>()
.ToMethod(ctx => ctx.Kernel.Get<IConfigurationProvider<ISettings>>().Settings)
.InRequestScope();
编辑 2
我想我已经接近了,但仍然遇到了一些问题。我创建了一个自定义绑定(bind)生成器:
public class SettingsBindGenerator : IBindingGenerator
{
static readonly MethodInfo BuildMethod = typeof(SettingsBindGenerator).GetMethod(
"BuildRegistration",
BindingFlags.Static | BindingFlags.NonPublic);
public IEnumerable<IBindingWhenInNamedWithOrOnSyntax<object>> CreateBindings(Type type, IBindingRoot bindingRoot)
{
var obj = typeof (object).IsAssignableFrom(type);
if (type != null && typeof(ISettings).IsAssignableFrom(type))
{
var buildMethod = BuildMethod.MakeGenericMethod(type);
var methodResult = buildMethod.Invoke(null, new object[]{bindingRoot});
var castedResult = methodResult as IBindingWhenInNamedWithOrOnSyntax<object>;
yield return castedResult;
}
}
static IBindingWhenInNamedWithOrOnSyntax<TSettings> BuildRegistration<TSettings>(IBindingRoot bindingRoot) where TSettings : ISettings, new()
{
return bindingRoot.Bind<TSettings>().ToMethod(
ctx => ctx.Kernel.Get<IConfigurationProvider<TSettings>>().Settings);
}
}
这对 99% 有效。但是,出于某种原因,buildMethod.Invoke 返回 BindingConfigurationBuilder,而不是 IBindingWhenInNamedWithOrOnSyntax。因此,castedResult 始终为 NULL。有人知道如何纠正这个问题吗?
最后编辑
不知道为什么,突然就可以了!很高兴我终于想通了。谢谢雷莫!
最佳答案
您有多种选择:
- 像 NopCommerce 一样,扫描设置类,并使用反射从您的第一次编辑中调用注册方法。
- 使用约定扩展注册所有使用自定义绑定(bind)生成器实现
ISettings
的类 https://github.com/ninject/ninject.extensions.conventions/wiki/Projecting-Services-to-Bind - 使用约定扩展来注册所有实现
ISettings
的类以绑定(bind)所有接口(interface)。并向 Ninject 添加自定义 IActivationStrategy,它会像 NopCommerce 那样分配属性。
关于c# - Ninject 中的泛型和属性绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14823810/