Abhishek Vyas
Abhishek Vyas

Reputation: 734

Is there a better way to implement dependencies?

Below is my use case:

Employee Management is a separate C# class library project. And there is a setting for Employee Management at application level. It means there is a global Boolean variable isEmployeeManagement

If the variable is true, then all the code related with Management used across whole application should get executed for e.g.

IEmployeeManagement.AddUser();
IEmployeeManagement.DeleteUser();

But if the setting is false then; the below lines should not through any exception. One of the approaches I thought of is like checking the condition.

If (isEmployeeManagement)
  IEmployeeManagement.AddUser();

But I want to achieve this using Interfaces without putting any code in the condition. So if the setting is false, the above code should not through any error.

Appreciate if you could help me with the implementation.

Upvotes: 0

Views: 50

Answers (1)

Erndob
Erndob

Reputation: 2612

So if you have the interface IEmployeeManagement:

public interface IEmployeeManagement {
    void AddUser();
}

And then you have your class that implements it:

public class RealManagement : IEmployeeManagement {
    public void AddUser() {  do lots of stuff  }
}

Instead of having an if condition for each AddUser call, make another interface implementation:

public class VoidManagement : IEmployeeManagement {
    public void AddUser() {  do nothing  }
}

This way you won't need to do if conditions on each method call, and instead you will do it only on class initialization.

If you use some kind of dependency injection framework, you can have that logic set only once instead, of on each class creation.

If the setting is on entire application level, for all users, you could have something like this

Startup.cs(assuming .net core):

public void ConfigureServices(IServiceCollection services)
        {
            if(Configuration["isEmployeeManagement"] == "true") {
                services.AddTransient<IEmployeeManagement>(RealManagement);
            } else {
                services.AddTransient<IEmployeeManagement>(VoidManagement);
            }
        }

How to exactly do initialization of correct instance changes based on how you get that isEmployeeManagement, what is the lifespan of the service, and what DI library you are using, if using anything. But the overall idea is same - two implementations of interface, call the methods where you need to, but use some kind of logic to have correct initialization of the instance.

Upvotes: 1

Related Questions