by zubspace · 7y ago · 0 comments
So why not make it a singleton? Or even better, make it a static class with some static properties?
Yes I know, I said something evil! But before you take out the pitchforks, bear with me:
public static class Master
{
public static ISupplyService Supply;
public static IBankService Bank;
public static IMailService Mailer;
}
This is C# and I actually LOVE this pattern. I have seen it referred to as Master-Pattern, but I don't know the correct term. It solves a lot of problems:* You don't have to pass essential modules around anymore. You can initialize the Master once and access them everywhere without caring about their implementation.
* Code completion does wonders on this one. You simply type "Mast..." and it will show you ALL available modules. You don't have to remember anything. It's awesome for new team members.
* It is fast. In release builds you can even try to replace the interfaces with the actual classes implementing it for a straight method call.
It introduces a few problems:
* You increase coupling. Once you add a module, removing it or significantly changing the interface is tricky.
* You need to be careful to NOT couple modules to each other, and if you do, do it rarely. Otherwise you will have to instantiate the modules in a specific order which gets cumbersome.
In my opinion: If you are a small team and have sane teammates, give this one a try. It reduces boilerplate a lot and reduces the amount of arguments you need to pass around everywhere.
So you could use a good DI framework such as SimpleInjector and get all the benefits without all the problems. You only have to initialize once, and then it's injected into constructors when needed, and you can inject different implementations depending on context.
So this has the advantages and disadvantages of that.
This is much harder to do when everything is a static.
Edit: some typos.
Isn't the interface mainly for the compiler, and in runtime it's just a straight method call anyways?