如何将实现细节正确解耦到 .net 中的类库中
我想知道 c#(甚至可能是 cli)中是否有一种标准方法可以有效地将实现逻辑解耦到单独的类库/程序集中,这些类库/程序集将由一个进程动态加载,该进程将基于通用接口对这些库执行操作。
更准确地说: 假设我正在构建一个接收消息的服务,并将这些消息的处理委托给其他东西。就像:
while(true){
message = read_message_from_somewhere();
class_from_another_lib.do_somthing_with_Message(message);
}
我希望进程在运行时从某种配置加载类库。我认为,lib 会有一些主类或类工厂,它们实现了一些接口部分,如下所示:
ISomePublicIface{
void do_somthing_with_Message(messageT);
}
这一切都感觉有些 java beish,我需要做的就是让程序集中的类实现某种类型可注入接口向应用程序配置添加一行并免费获得大量内容。
I'm wondering if there is a standard way in c#(or maybe even cli) to efficiently decouple implementation logic into separate class libraries/assemblies that would be dynamically loaded by a process that will preforms actions on those libraries based on a common interface.
More precisely:
Say I'm building a service that receives messages, and delegates handling of these messages to something else. Something like:
while(true){
message = read_message_from_somewhere();
class_from_another_lib.do_somthing_with_Message(message);
}
I want the process to load a class lib in runtime from some sort of config. The lib, I assume, would have some main class or class factory that implements some interface part of which looks like this:
ISomePublicIface{
void do_somthing_with_Message(messageT);
}
This all feels somewhat java beenish where all I would need to do is have the a class in an assembly implement some sort of injectable interface add a line to the app config and get abunch of stuff for free.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查看托管扩展性框架 (MEF),它包含在 .NET 4.0 中。 MEF 可以从外部 DLL 动态加载和注入组件。
Take a look at the Managed Extensibility Framework (MEF), which is included in .NET 4.0. MEF can dynamically load and inject components from external DLLs.
如果您喜欢 NIH 解决方案...我已经编写了这个问题的稍微详细的版本,它允许您使用 DI 容器来存储消息的处理程序并根据消息分派到相关处理程序。我在这里使用 autofac 作为容器,但只要它可以解决开放泛型,任何东西都应该是合适的:
您显然希望从 Main 中提取一些问题,但它应该为您提供问题和解决方案的要点。
If you fancy a NIH solution... I've written up a slightly verbose version of this problem which allows you to use a DI container to store handlers for the message and dispatch to the relevant handler based on message. I've used autofac for the container here, but anything should be suitable as long as it can resolve open generics:
You will obviously want to extract the concerns out a little from Main but it should give you the gist of the problem and solution.