简体   繁体   English

如何指出项目中要在类库组件中执行的方法

[英]How to point out to a method in project to be executed inside a class library component

In the past I had quite some reusable code in my project which I would like to put inside a custom class library project so other projects can reuse it. 过去,我的项目中有很多可重用的代码,我想将它们放入自定义类库项目中,以便其他项目可以重用它。 There is only just one piece of code which needs configuration in code which is project dependent. 只有一小段代码需要在与项目相关的代码中进行配置。

How can I inject a method to be executed in my project inside a method of the class library? 如何在类库的方法内注入要在项目中执行的方法? I was thinking about using a delegate but am open for suggestions. 我当时正在考虑使用委托人,但愿意征求建议。 If you have some code, I am not that great with delegates, please post as well. 如果您有一些代码,代表们对我的要求不高,请也发帖。

You're looking for different ways to achieve IOC/Dependency Injection . 您正在寻找实现IOC /依赖注入的不同方法。 A common way is to take a parameter which implements: 一种常见的方法是采用一个实现以下参数的参数:

interface IDoSomething
{
   void DoSomething(string myParam);
}

class MyLibrary
{
    public void DoLibraryStuff(IDoSomething iDoSomething, string extraParam)
    { iDoSomething.DoSomething("info");... }
}

If you'd like to use delegates you could use: 如果您想使用委托,可以使用:

class MyLibrary
{
    public void DoLibraryStuff(Action<string> doSomething, string extraParam)
    { doSomething("info");... }
}

Usage: 用法:

new MyLibrary().DoLibraryStuff(info => Console.WriteLine(info), "extraParam");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM