Is there a better way to implement dependencies?What is an efficient way to implement a singleton pattern in Java?What is dependency injection?What is the best way to iterate over a dictionary?C# Interfaces. Implicit implementation versus Explicit implementationDependency Injection vs Factory PatternImplementing INotifyPropertyChanged - does a better way exist?How to determine if a type implements an interface with C# reflectionImplements vs extends: When to use? What's the difference?Does anyone have benchmarks (code & results) comparing performance of Android apps written in Xamarin C# and Java?inline conditional check to apply extension to variable?

How major are these paintwork & rust problems?

In Germany, how can I maximize the impact of my charitable donations?

Bash, import output from command as command

Make 1998 using the least possible digits 8

Make 2019 with single digits

Write a function that returns an iterable object of all valid points 4-directionally adjacent to (x, y)

If the gambler's fallacy is false, how do notions of "expected number" of events work?

Relocation error involving libgnutls.so.30, error code (127) after last updates

Can I toggle Do Not Disturb on/off on my Mac as easily as I can on my iPhone?

Why don't Wizards use wrist straps to protect against disarming charms?

What was redacted in the Yellowhammer report? (Point 15)

What is a realistic time needed to get a properly trained army?

Why is the T-1000 humanoid?

Is the Dodge action perceptible to other characters?

What exactly is a marshrutka (маршрутка)?

3d printed bricks quality?

A medieval fantasy adventurer lights a torch in a 100% pure oxygen room. What happens?

How to publish superseding results without creating enemies

How are aircraft depainted?

What officially disallows US presidents from driving?

Cannot find Database Mail feature in SQL Server Express 2012 SP1

How does a simple logistic regression model achieve a 92% classification accuracy on MNIST?

How do EVA suits manage water excretion?

Planar regular languages



Is there a better way to implement dependencies?


What is an efficient way to implement a singleton pattern in Java?What is dependency injection?What is the best way to iterate over a dictionary?C# Interfaces. Implicit implementation versus Explicit implementationDependency Injection vs Factory PatternImplementing INotifyPropertyChanged - does a better way exist?How to determine if a type implements an interface with C# reflectionImplements vs extends: When to use? What's the difference?Does anyone have benchmarks (code & results) comparing performance of Android apps written in Xamarin C# and Java?inline conditional check to apply extension to variable?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















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.










share|improve this question
























  • You can write an interface which store this variable, write it's implementation and pass interface as a dependency to employee management. You also can use any of DI containers, register this like single instance and pass through constructor injection

    – Pavel Anikhouski
    Mar 28 at 9:41











  • Pavel, possible to share code example?

    – Abhishek
    Mar 28 at 10:00











  • there is a small example dotnetfiddle.net/Widget/pHWFgq

    – Pavel Anikhouski
    Mar 28 at 10:31












  • Hi Pavel, appreciate your reply. Well, In that code, the problem is, I still have to use that if condition in all the methods.

    – Abhishek
    Mar 28 at 11:09


















0















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.










share|improve this question
























  • You can write an interface which store this variable, write it's implementation and pass interface as a dependency to employee management. You also can use any of DI containers, register this like single instance and pass through constructor injection

    – Pavel Anikhouski
    Mar 28 at 9:41











  • Pavel, possible to share code example?

    – Abhishek
    Mar 28 at 10:00











  • there is a small example dotnetfiddle.net/Widget/pHWFgq

    – Pavel Anikhouski
    Mar 28 at 10:31












  • Hi Pavel, appreciate your reply. Well, In that code, the problem is, I still have to use that if condition in all the methods.

    – Abhishek
    Mar 28 at 11:09














0












0








0








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.










share|improve this question














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.







c# design-patterns interface abstract-class






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 28 at 9:37









AbhishekAbhishek

631 gold badge2 silver badges8 bronze badges




631 gold badge2 silver badges8 bronze badges















  • You can write an interface which store this variable, write it's implementation and pass interface as a dependency to employee management. You also can use any of DI containers, register this like single instance and pass through constructor injection

    – Pavel Anikhouski
    Mar 28 at 9:41











  • Pavel, possible to share code example?

    – Abhishek
    Mar 28 at 10:00











  • there is a small example dotnetfiddle.net/Widget/pHWFgq

    – Pavel Anikhouski
    Mar 28 at 10:31












  • Hi Pavel, appreciate your reply. Well, In that code, the problem is, I still have to use that if condition in all the methods.

    – Abhishek
    Mar 28 at 11:09


















  • You can write an interface which store this variable, write it's implementation and pass interface as a dependency to employee management. You also can use any of DI containers, register this like single instance and pass through constructor injection

    – Pavel Anikhouski
    Mar 28 at 9:41











  • Pavel, possible to share code example?

    – Abhishek
    Mar 28 at 10:00











  • there is a small example dotnetfiddle.net/Widget/pHWFgq

    – Pavel Anikhouski
    Mar 28 at 10:31












  • Hi Pavel, appreciate your reply. Well, In that code, the problem is, I still have to use that if condition in all the methods.

    – Abhishek
    Mar 28 at 11:09

















You can write an interface which store this variable, write it's implementation and pass interface as a dependency to employee management. You also can use any of DI containers, register this like single instance and pass through constructor injection

– Pavel Anikhouski
Mar 28 at 9:41





You can write an interface which store this variable, write it's implementation and pass interface as a dependency to employee management. You also can use any of DI containers, register this like single instance and pass through constructor injection

– Pavel Anikhouski
Mar 28 at 9:41













Pavel, possible to share code example?

– Abhishek
Mar 28 at 10:00





Pavel, possible to share code example?

– Abhishek
Mar 28 at 10:00













there is a small example dotnetfiddle.net/Widget/pHWFgq

– Pavel Anikhouski
Mar 28 at 10:31






there is a small example dotnetfiddle.net/Widget/pHWFgq

– Pavel Anikhouski
Mar 28 at 10:31














Hi Pavel, appreciate your reply. Well, In that code, the problem is, I still have to use that if condition in all the methods.

– Abhishek
Mar 28 at 11:09






Hi Pavel, appreciate your reply. Well, In that code, the problem is, I still have to use that if condition in all the methods.

– Abhishek
Mar 28 at 11:09













1 Answer
1






active

oldest

votes


















1
















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.






share|improve this answer


























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );














    draft saved

    draft discarded
















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55394305%2fis-there-a-better-way-to-implement-dependencies%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1
















    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.






    share|improve this answer































      1
















      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.






      share|improve this answer





























        1














        1










        1









        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.






        share|improve this answer















        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.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 28 at 10:27

























        answered Mar 28 at 10:16









        ErndobErndob

        1,72710 silver badges22 bronze badges




        1,72710 silver badges22 bronze badges





















            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.




















            draft saved

            draft discarded















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55394305%2fis-there-a-better-way-to-implement-dependencies%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript