[英]Constructor injected implementation has a dll dependency which is not used
As you know, Ninject binds all interfaces to implementations in the composition root. 如您所知,Ninject将所有接口绑定到组合根中的实现。 We have a class which is dependent on an external dll, but we don't want to deploy it (the physical dll file in the bin directory) if it's not being used.
我们有一个依赖于外部dll的类,但如果没有使用它我们不想部署它(bin目录中的物理dll文件)。 The class
ExampleClass
is stored in our Framework project, this means it's referenced by any application we are building. ExampleClass
类存储在我们的Framework项目中,这意味着它被我们正在构建的任何应用程序引用。 And that's why we are getting the following when deploying any of our application: 这就是我们在部署任何应用程序时获得以下内容的原因:
Could not load file or assembly ExternalDll, Version=xxxxxx, Culture=neutral, PublicKeyToken=xxxxxxxxxxxxxxxx
无法加载文件或程序集ExternalDll,Version = xxxxxx,Culture = neutral,PublicKeyToken = xxxxxxxxxxxxxxxx
Is there any workaround, like encapsulating the implementation into another class or something? 有没有解决方法,比如将实现封装到另一个类或其他类中? Or runtime initialisation (Factory pattern).
或运行时初始化(工厂模式)。 Which of these will solve my problem?
以下哪一项可以解决我的问题? I also tried Lazy binding but without success.
我也试过Lazy绑定但没有成功。
Constructor injection of implementation where the external dll is being used 构造函数注入正在使用外部dll的实现
namespace Framework
{
public class ExampleClass
{
private readonly IUsesExternalDll _usesExternalDll;
public ExampleClass(IUsesExternalDll usesExternalDll)
{
_usesExternalDll = usesExternalDll;
}
}
}
Interface 接口
public interface IUsesExternalDll
{
}
Implementation 履行
using externalDll; //this using is a reference to external dll
public class UsesExternalDll : IUsesExternalDll
{
}
Binding 捆绑
kernel.Bind<IUsesExternalDll>().To<UsesExternalDll>().InTransientScope();
You can replace your binding with convention binding: 您可以使用约定绑定替换绑定:
kernel.Bind(x => x.FromAssembliesMatching("AssemblyWhereUsesExternalDllIsLocated.dll")
.SelectAllClasses()
.BindAllInterfaces()
.Configure(c => c.InTransientScope()));
Now types inside are bound only when this assembly is found. 现在只有在找到此程序集时才绑定内部类型。
How I solved this: 我怎么解决这个问题:
1) Move the Ninject binding to the specific application where it is used (higher level). 1)将Ninject绑定移动到使用它的特定应用程序(更高级别)。
2) Make the constructor injected parameter Optional
. 2)使构造函数注入参数
Optional
。
namespace Framework
{
public class ExampleClass
{
private readonly IUsesExternalDll _usesExternalDll;
public ExampleClass([Optional] IUsesExternalDll usesExternalDll)
{
_usesExternalDll = usesExternalDll;
}
}
}
Optional Attribute will lead to only being instantiated if there is a binding. 如果存在绑定,则可选属性将仅导致实例化。 And since I moved the bindings to the specific application where it is being used, in all other applications I won't get the
Could not load file or assembly
error because UsesExternalDll
is not instantiated. 因为我将绑定移动到正在使用它的特定应用程序,所以在所有其他应用程序中,我不会得到
Could not load file or assembly
错误,因为UsesExternalDll
未实例化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.