C # dependency injection - how do you inject a dependency without a source?

I am trying to start with some simple dependency injection using C #, and I ran into a problem that I seem to be unable to answer.

I have a class written by another department for which I have no source in my project. I wanted to introduce an object of this type, although a constructor using an interface, but, of course, I cannot change the implementation of embedded objects to implement an interface to achieve polymorphism when throwing an object into an interface type.

In every academic example I have ever seen in this technique, classes use the classes declared in the project itself. How will I introduce my dependency without the source available in the project?

I hope this makes sense, thanks.

+5
source share
3 answers

You can create a wrapper around your target type, for example, you can have a class that they provide:

public class TheirClass
{
  public void DoSomething();
}

With the help of which you can define the interface:

public interface ITheirClass
{
  void DoSomething();
}

And implement this interface in a wrapper class:

public class TheirClassWrapper : TheirClass, ITheirClass
{

}

Or, if the class they provided is sealed, you need to do it a little differently:

public class TheirClassWrapper : ITheirClass
{
  private TheirClass instance = new TheirClass();

  public void DoSomething()
  {
    instance.DoSomething();
  }
}

You can then enter this interface instead.

I know that in MEF we can export specific types and enter them correctly, but I'm not sure about other IoC containers.

+6
source

, ? , /, , , "" , " , ",? , , , , , .

, :

  • . , , .
  • , /, , , .

2, , , , ( Method1()), :

public interface IMyNewInterface
{
    void Method1();
}

, ( ), :

public class MyNewClass : IMyNewInterface
{
    private MyConcreteClass _MyConcreteClass;

    public void MyNewClass(MyConcreteClass concreteClass)
    {
        _MyConcreteClass = concreteClass;
    }

    public void Method1()
    {
        _MyConcreteClass.Method1();
    }
}
+1

- , . , X DLL, Y, . X Y. :

DLL, X .

Use NameSpaceOfX;
Class Y
{
    Public Y() //Default constructor
    {
    }

    Public Y(X instanceOfX)
    {
        //Use instanceOfX here as required
    }
}

:

//Create instance of X
X instanceOfX = new X();
//Inject it into Y
Y instanceOfY = new Y(instanceOfX);
//Use Y now.
0

All Articles