Ninject动态绑定到实现

时间:2015-09-07 11:21:13

标签: c# ninject ninject-extensions ninject-conventions

有几个问题在SO上是相似但不完全是我正在寻找的。我想根据运行时条件进行Ninject绑定,这在启动时是不可预知的。关于动态绑定的SO的其他问题围绕基于配置文件或某些类似的绑定 - 我需要在处理特定实体的数据时基于数据库值有条件地发生。如,

public class Partner
{
    public int PartnerID { get; set; }
    public string ExportImplementationAssembly { get; set; }
}

public interface IExport
{
    void ExportData(DataTable data);
}

在其他地方,我有两个实现IExport的dll

public PartnerAExport : IExport
{
    private readonly _db;
    public PartnerAExport(PAEntities db)
    {
        _db = db;
    }
    public void ExportData(DataTable data)
    {
        // export parter A's data...
    }
}

然后是伙伴B;

public PartnerBExport : IExport
{
    private readonly _db;
    public PartnerBExport(PAEntities db)
    {
        _db = db;
    }
    public void ExportData(DataTable data)
    {
        // export parter B's data...
    }
}

目前的Ninject绑定是;

public class NinjectWebBindingsModule : NinjectModule
{
    public override void Load()
    {
        Bind<PADBEntities>().ToSelf();
        Kernel.Bind(s => s.FromAssembliesMatching("PartnerAdapter.*.dll")
                          .SelectAllClasses()
                          .BindDefaultInterfaces()
                   );
    }
}

那么如何设置我可以做的绑定;

foreach (Partner partner in _db.Partners)
{
    // pseudocode...
    IExport exportModule = ninject.Resolve<IExport>(partner.ExportImplementationAssembly);
    exportModule.ExportData(_db.GetPartnerData(partner.PartnerID));
}

这可能吗?它似乎应该是,但我不能完全理解如何去做。上面的现有绑定配置适用于静态绑定,但我需要一些我可以在运行时解决的东西。以上是可能的还是我只是想绕过Ninject并使用旧式反射加载插件?如果是这样,我如何使用该方法通过Ninject解析任何构造函数参数,如同静态绑定对象一样?

更新:我已使用BatteryBackupUnit的解决方案更新了我的代码,以便我现在拥有以下内容;

Bind<PADBEntities>().ToSelf().InRequestScope();
Kernel.Bind(s => s.FromAssembliesMatching("PartnerAdapter.*.dll")
                    .SelectAllClasses()
                    .BindDefaultInterfaces()
                    .Configure(c => c.InRequestScope())
            );

Kernel.Bind(s => s.FromAssembliesMatching("PartnerAdapter.Modules.*.dll")
                    .SelectAllClasses()
                    .InheritedFrom<IExportService>()
                    .BindSelection((type, baseTypes) => new[] { typeof(IExportService) })
            );
Kernel.Bind<IExportServiceDictionary>().To<ExportServiceDictionary>().InSingletonScope();
ExportServiceDictionary dictionary = KernelInstance.Get<ExportServiceDictionary>();

在2个测试模块中实例化导出实现可以正常工作并实例化PADBEntites上下文。但是,我的服务层中的所有其他绑定现在不再适用于系统的其余部分。同样,如果我将PADBEntities变量/ ctor参数更改为ISomeEntityService组件,则无法绑定导出层。我似乎错过了配置绑定以使其工作的最后一步。有什么想法吗?

错误:&#34;激活ISomeEntityService时出错。没有匹配的绑定可用且类型不可自我绑定&#34;

更新2 :最终使用BatteryBackupUnit的解决方案进行了一些试验和错误,但我对跳跃不太满意思想。欢迎任何其他更简洁的解决方案。

我改变了原来的约束;

        Kernel.Bind(s => s.FromAssembliesMatching("PartnerAdapter.*.dll")
                          .SelectAllClasses()
                          .BindDefaultInterfaces()
                   );

更加详细和明确;

Bind<IActionService>().To<ActionService>().InRequestScope();
Bind<IAuditedActionService>().To<AuditedActionService>().InRequestScope();
Bind<ICallService>().To<CallService>().InRequestScope();
Bind<ICompanyService>().To<CompanyService>().InRequestScope();
//...and so on for 30+ lines

不是我最喜欢的解决方案,但它适用于基于显式和约定的绑定,但不适用于两种约定。任何人都可以看到我在绑定中出错了吗?

更新3 :忽略Update 2中绑定的问题。看来我在Ninject中发现了一个与引用库中有多个绑定模块有关的错误。模块A的更改,即使从未通过断点点击,也会使用不同的模块明确地破坏项目B.去图。

2 个答案:

答案 0 :(得分:3)

重要的是要注意,虽然实际的“条件匹配”是运行时条件,但实际上您实际上知道可能的匹配集(至少在构建容器时启动) - 这可以通过使用约定来证明。这就是条件/上下文绑定的含义(在Ninject WIKI中有描述,并在几个问题中有所介绍)。所以你实际上不需要在任意运行时间进行绑定,而只需要在任意时间进行分辨率/选择(分辨率实际上可以提前完成=&gt;提前失败)。

这是一个可能的解决方案,其特点是:

  • 在启动时创建所有绑定
  • 提前失败:验证启动时的绑定(通过实例化所有绑定的IExport
  • 在任意运行时选择IExport

internal interface IExportDictionary
{
    IExport Get(string key);
}

internal class ExportDictionary : IExportDictionary
{
    private readonly Dictionary<string, IExport> dictionary;

    public ExportDictionary(IEnumerable<IExport> exports)
    {
        dictionary = new Dictionary<string, IExport>();
        foreach (IExport export in exports)
        {
            dictionary.Add(export.GetType().Assembly.FullName, export);
        }
    }

    public IExport Get(string key)
    {
        return dictionary[key];
    }
}

作文根:

// this is just going to bind the IExports.
// If other types need to be bound, go ahead and adapt this or add other bindings.
kernel.Bind(s => s.FromAssembliesMatching("PartnerAdapter.*.dll")
        .SelectAllClasses()
        .InheritedFrom<IExport>()
        .BindSelection((type, baseTypes) => new[] { typeof(IExport) }));

kernel.Bind<IExportDictionary>().To<ExportDictionary>().InSingletonScope();

// create the dictionary immediately after the kernel is initialized.
// do this in the "composition root".
// why? creation of the dictionary will lead to creation of all `IExport`
// that means if one cannot be created because a binding is missing (or such)
// it will fail here (=> fail early).
var exportDictionary = kernel.Get<IExportDictionary>(); 

现在IExportDictionary可以注入任何组件,只需像“必需”一样使用:

foreach (Partner partner in _db.Partners)
{
    // pseudocode...
    IExport exportModule = exportDictionary.Get(partner.ExportImplementationAssembly);
    exportModule.ExportData(_db.GetPartnerData(partner.PartnerID));
}

答案 1 :(得分:2)

  

我想根据运行时条件进行Ninject绑定,但在启动时不会预先知道。

防止在构建对象图期间做出运行时决策。这会使您的配置复杂化并使您的配置难以验证。理想情况下,您的对象图应该是固定的,不应该在运行时改变形状。

相反,通过将其移动到IExport的代理类,在运行时进行运行时决策。这样的代理究竟是什么样的,取决于你的确切情况,但这是一个例子:

public sealed class ExportProxy : IExport
{
    private readonly IExport export1;
    private readonly IExport export2;
    public ExportProxy(IExport export1, IExport export2) {
        this.export1 = export1;
        this.export2 = export2;
    }

    void IExport.ExportData(Partner partner) {
        IExport exportModule = GetExportModule(partner.ExportImplementationAssembly);
        exportModule.ExportData(partner);
    }

    private IExport GetExportModule(ImplementationAssembly assembly) {
        if (assembly.Name = "A") return this.export1;
        if (assembly.Name = "B") return this.export2;
        throw new InvalidOperationException(assembly.Name);
    }
}

或许您正在处理一组动态确定的程序集。在这种情况下,您可以为代理提供导出提供程序委托。例如:

public sealed class ExportProxy : IExport
{
    private readonly Func<ImplementationAssembly, IExport> exportProvider;
    public ExportProxy(Func<ImplementationAssembly, IExport> exportProvider) {
        this.exportProvider = exportProvider;
    }

    void IExport.ExportData(Partner partner) {
        IExport exportModule = this.exportProvider(partner.ExportImplementationAssembly);
        exportModule.ExportData(partner);
    }
}

通过向代理提供Func<,>,您仍然可以在注册ExportProxy(组合根)的位置做出决定,您可以在其中查询系统的程序集。这样,您可以在容器中预先注册IExport实现,从而提高配置的可验证性。如果您使用密钥注册了所有IExport实施,则可以对ExportProxy进行以下简单注册

kernel.Bind<IExport>().ToInstance(new ExportProxy(
    assembly => kernel.Get<IExport>(assembly.Name)));
相关问题