I have multiple objects that are used by several classes in my BL.
I'm tring to understand how those objects should be instansiated and where to store them.
I don't want to pass them from the Service layer. My thoughs are to create a singleton class in the BL and all the others would use it. Is it a reasonable solution? I know many think of the singleton as an anti patten.
Thanks
Don't use singleton or static. It prevents your class from dependency injected and inflexible. I.e: you cannot change the class behavior based on component.
The best is to use constructor injection:
public class Usage{
public Usage(Component1 comp1, Component2 comp2){ /*param assignment*/ }
private Component1 comp1;
private Component2 comp2;
//using comp1 and comp2
}
Or if you think that it is bothersome for object composition, you can use default object creation, that is commonly used by .Net.
public class Usage{
public Component1 Comp1 = new Component1();
public Component2 Comp2 = new Component2();
//using Comp1 and Comp2
}
The benefit is, you can change Components
with it's inheritance
, or you can use interface as declaration instead for better flexibility.