Delegates vs Interface – DI

  • The one advantage that passing an interface to the constructor would have is it makes the dependency resolution easier to declare in a DI framework. If a have a class like.
				
					/*The biggest difference delegate and interfaces...*/
delegate void XYZ(int p);

interface IXyz {
    void doit(int p);
}

class One {
    // All four methods below can be used to implement the XYZ delegate
    void XYZ1(int p) {...}
    void XYZ2(int p) {...}
    void XYZ3(int p) {...}
    void XYZ4(int p) {...}
}

class Two : IXyz {
    public void doit(int p) {
        // Only this method could be used to call an implementation through an interface
    }
}
				
			

Interface

				
					public class ClassA{
    public ClassA(IInterface interface){
    ...
    }
}

container.RegisterType<IInterface, ConcreteImplementation>();
				
			

Delegate

				
					public class ClassA{
    public ClassA(Delegate delegateInstance){
    ...
    }
}

//to resigster delegate is not straightforward....

 container.RegisterType<ClassA>(
     new InjectionFactory(a => {
         return new ClassA(()=>{/*delegate code*/});
 }));
				
			

Leave a Comment