views:

20

answers:

1

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.

+3  A: 

You're looking for different ways to achieve IOC/Dependency Injection. 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");
Yuriy Faktorovich
Looks interesting. I will take a look at this. I am not really familiar with IOC but a quick google showed me that in .NET one can have different flavors like Ninject and Unity. What is preferred?
Nyla Pareska
@Nyla Pareska: I'm not quite sure, but I don't think a framework is what you're looking for in this case. Frameworks seem to be more for more general case than what you cited. Personally, I prefer PostSharp.
Yuriy Faktorovich
I am just in the testing phase hence my questions but ultimately I hope it to become a framework like thing. Also I am just learning, or trying to, some .NET techniques.
Nyla Pareska
How can I put paramaters into the method DoSomething? I am not succeeding at that.
Nyla Pareska
@Nyla Pareska: Modified both versions with parameters.
Yuriy Faktorovich
Thank you but I mean to pass in a parameter from the side of the console application. Can I specify which method to be called because now it seems the method is hard coded in the library.
Nyla Pareska
@Nyla Pareska you can specify which method is called by passing different class implementations of the interface.
Yuriy Faktorovich
I am trying that but how do I pass in the parameter then? Via a property of the class that implements the interface? Sorry but I am a bit at loss here.
Nyla Pareska
@Nyla Pareska: I've modified, but I'm still not sure I have what you're looking for. Can you explain your use case a bit further.
Yuriy Faktorovich
Thank you for your help and patience with me. I am not completely fully understanding the code, especially the second one but the first solution seems to work out for me.
Nyla Pareska