0

I am new to Dependency injection Pattern. Please look in to the below scenario. Right now, my below code is in tightly coupled. I want to make this as lightly coupled.

Could someone help me out to implement dependency injection using Unity?

// Implementation of class A
public class A
{
  public B b{get;set;}
  public A(B b,string c)
  {
     this.b=b;
     this.A(b,c);
  }
}

//Implementation of Class B
public class B
{
    public int value1 {get;private set;}
    public string stringValue {get;private set;}

    public B(int value,string strValue)
    {
       this.value1=value;
       this.stringValue=strValue;
    }
}
//Implementation of class C
public class C
{   
  public void Dosomething()
  {
     B b=null;
     string value="Something";
     // Here I need to implement unity to resolve tight coupling 
     // without creating  object of Class A
     A a=new A(b,value); 

  }
}

I tired something based on the blow possible duplicate question. But still I am facing same issue.

How should I register this type that has parameterized constructor, in Unity?

Instead of this line, I have implemented the below code

     A a=new A(b,value); 

var container=new UnityContainer();
container.RegisterType<A>();
container.RegisterType<B>();
A a=new A(b,container.ResolveType<B>();

But its not helping me out.

1

1 Answer 1

1

Firstly, I would start be advising that you further decouple your classes by introducing Interfaces, so you could implement class C as follows:

 public class C
{
    private readonly IA a;

    private readonly IB b;

    public C(IA a, IB b)
    {
        this.a = a;
        this.b = b;
    }

    public void Dosomething()
    {
        // do something with this.a or this.b.
    }
}

You could then register and resolve your classes as below:

var container = new UnityContainer();

        container.RegisterType<IB, B>(new InjectionConstructor(1, "Test"));
        container.RegisterType<IA, A>(new InjectionConstructor(new ResolvedParameter<IB>(),"Test"));
        container.RegisterType<IC, C>();

        var c = container.Resolve<IC>();

Although I would recommend the above approach, as an alternative, you can also stipulate the injection values when you resolve, for example:

container.RegisterType<IB, B>();

container.Resolve<IB>(
            new ParameterOverride("value", 1), 
            new ParameterOverride("strValue", "Test"));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.