hyperar
hyperar

Reputation: 47

Injecting objects into forms

I'm developing a WinForms app, and i need to have some objects in every form, and i don't want to initialize each object on every form so, i created a base class:

public class FormBase : Form
{
    #region Properties

    public BusinessLogic.ChppManager ChppManager { get; protected set; }
    public BusinessLogic.DatabaseManager DatabaseManager { get; protected set; }
    public BusinessLogic.FileManager FileManager { get; protected set; }
    public BusinessLogic.RegistryManager RegistryManager { get; protected set; }

    #endregion Properties
}

And i pass each of those objects on the constructor. It works, but i wanted to know if there's an easier (standard) way to do this, without passing those parameters on every constructor call.

Thanks in advance.

Upvotes: 2

Views: 338

Answers (2)

Steven
Steven

Reputation: 172875

The advised way is to not do this. Such base class with these dependencies is a code smell, because you are hiding the fact that the Form implementations use too many dependencies, which is an indication of violating the Single Responsibility Principle. Violations of the SRP often lead to harder to grasp, hard to maintain code.

Instead, prevent having a base class that takes these 'default' dependencies. If a class needs to use some service, inject it into the constructor. If a class needs too many dependencies, it's an indication of a SRP violation and you should investigate and refactor; for instance to aggregate services.

Upvotes: 0

toadflakz
toadflakz

Reputation: 7934

If you use a dependency injection container like Unity to use constructor resolution of the constructor parameters, you would load the initialized objects into the Unity container and then use the Resolve<T>() method to resolve the dependencies at runtime meaning you don't have to specify them as parameters in your code - they would still need to be part of the constructor signature however.

If you abstract those Unity-resolved classes out to interfaces, it means that you could at a later stage change the underlying implementation so long as the interface remains the same.

Upvotes: 2

Related Questions