Dependency Injection in C# .NET

Dependency injection basically allows us to create loosely coupled, reusable, and testable objects in your software designs by removing dependencies.

We will take a look into the Object dependencies before digging in more.
Consider a scenario of fetching an employee details and show display in UI. Let us say create a Business logic layer class named EmployeeBAL and a data access layer class named EmployeeDAO

public class EmployeeDao
{
//Some code
}
public class EmployeeBAL
{
var employeeDAO = new EmployeeDao();
//Some code
}

From the above code you will notice one thing that we are creating EmployeeDAO instance inside the Business logic layer class. So here comes the dependency

What is wrong if we have a dependency?

Think about whether your code is unit testable. We cannot fully unit test the EmployeeBAL as it has a dependency on Employee DAO. So we can say as long as the composition of the DAO exists within the BAL we cannot unit test the EmployeeBAL.

You will also notice one more thing here; with this type of implementation you will see a high coupling of BAL and DAL.

How to make it loose coupling?

The basic idea behind Dependency Injection is that you should isolate the implementation of an object from the construction of objects on which it depends.

Coming to the example, we should be isolating the implementation of EmployeeBAL object and the construction of the dependent EmployeeDAO object.

We will see how we can make loosely coupled objects in detail

Constructor based dependency injection
We will have to modify the EmployeeBAL to accept an EmployeeDAO instance within its constructor.

public class EmployeeDao
{
//Some code
}

public class EmployeeBAL
{
EmployeeDao employeeDAO;
public EmployeeBAL(EmployeeDAO employeeDao){
this.employeeDAO = employeeDao;
}
//Some code
}

Property based dependency injection

With property based injection we will have a public getter and setter Property of type EmployeeDao so that the dependency can be externally set.
public class EmployeeBAL
{
Public EmployeeDao EmployeeDataAccess{ get; set; }
}
var employeeBAL = new EmployeeBAL();
EmployeeBAL.EmployeeDataAccess = new EmployeeDao();

Wait!!!

The above ones are just some techniques of injecting the dependency. We are still yet to discuss one more interesting thing Unit Testing.

Are you agreeing that we have removed the DAO creation from the Business Logic EmployeeBAL? Yes it is good but it still depends on the actual instance of EmployeeDao.

Consider the below mentioned implementation of the same sample senarios

interface IDataAccess
{
//Some code
}

class EmployeeDao : IDataAccess
{
//Some code
}

public class EmployeeBAL
{
private IDataAccess dataAccess;
public BusinessFacade(IDataAccess dao)
{
  dataAccess = dao;
}
}

You can notice we are doing a constructor dependency injection but most important thing here
is we are using Interface type than creating a strongly typed object.

The advantage that we are getting here is we can have an in memory data access object of
IDataAccess interface type and we can easily inject the dependency to the EmployeeBAL.

By this way we no need to have the actual database dependency.

Are you happy that we can unit test the BAL without the data access dependency?

Advantages of Dependency Injection

The primary advantages of dependency injection are:
Loose coupling
Centralized configuration
Easily testable

Another Post about DI: Understand Constructor Injection in Dependency Injection.

I found 1 more Link Usable-
Design pattern Inversion of control and Dependency

94 comments:

  1. Everyone wants to get unique place in the IT industry’s for that you need to upgrade your skills, your blog helps me improvise my skill set to get good career, keep sharing your thoughts with us.
    Regards,
    sas training in Chennai|sas course in Chennai|sas training institute in Chennai

    ReplyDelete
  2. very informative blog. Helps to gain knowledge about new concepts and techniques. Thanks for posting information in this blog
    Dotnet Training in Chennai

    ReplyDelete
  3. i need more clear cut concept in that topic it is really useful for many persons.


    software testing training in chennai


    ReplyDelete
  4. This blog is really informative. I gained more knowledge by reading your post. Thanks for providing us the useful information with us. Your blog is really helpful for me in attaining my knowledge in a right way.

    SAS Training in Chennai

    ReplyDelete
  5. Nice post. I have been reading a lot of stuff on this topic in the last few months, but this article stands out with its simplicity & authenticity. Every passage made profound sense. Thanks a lot for this

    ReplyDelete
  6. This is excellent information. It is amazing and wonderful to visit your site.Thanks for sharng this information,this is useful to me...
    Android Training in Chennai
    Ios Training in Chennai

    ReplyDelete
  7. Pretty article! I found some useful information in your blog, thanks for sharing this great content to my vision, keep sharing.. Software Testing Training in Chennai | Dot Net Training in Chennai | Web Design Training in Chennai

    ReplyDelete
  8. Nice Article Thanks for Shearing this Post,It is useful for me.
    sap training institute in gurgaon

    ReplyDelete
  9. I really love reading and following your post as I find them extremely informative and interesting. Java Training Center in Chennai | Best J2EE Training Center in Chennai | No.1 Java Training Institution in Velachery

    ReplyDelete
  10. Thanks for sharing such Valuable information on .Net technology. This post gives me detailed information about the .net technology.
    .net Training

    ReplyDelete
  11. Nice blog about .net technology. Helps to gain knowledge on .net learning new things. Thanks a lot
    ASP.net MVC Training

    ReplyDelete
  12. Thank you for taking the time to provide us with your valuable information. We strive to provide our candidates with excellent care and we take your comments to heart.As always, we appreciate your confidence and trust in us.
    Java Training in Chennai | Web Designing Training Institute in Chennai | DotNet Training Institute in Chennai

    ReplyDelete

  13. Impressive blog with lovely information. really very useful article for us thanks for sharing such a wonderful blog... 
    No.1 IOS Training Institute in Velachery | Best Android Training Institute in Velachery | Core Java Training Institute in Chennai

    ReplyDelete
  14. I believe there are many more pleasurable opportunities ahead for individuals that looked at your site.

    Hadoop Training institute in Bangalore

    ReplyDelete
  15. I believe there are many more pleasurable opportunities ahead for individuals that looked at your site.
    R Programming Training in Chennai
    R Programming

    ReplyDelete
  16. Thanks for sharing such informative on .Net technology. This post gives me unique information about the .net technology. I am working developer nareshit in Hyderabad Python training in Chennai

    ReplyDelete
  17. Thanks For Sharing Such A valuable Information About The C#.Net Technology.and Provide More Useful Information.

    ReplyDelete
  18. You Provided Very Nice Post About C#.Net Technology Thankyou For Sharing This One..i Learned More To this Post.

    Best Software Training Institute in Chennai

    Best Online Training Institute in Chennai

    ReplyDelete
  19. Thanks for sharing informative blog, it's very useful
    OnlineTraining

    ReplyDelete
  20. Thanks a lot for providing valuable information,i appreciate your work keep sharing.
    https://nareshit.in/software-training-institute-bangalore/

    ReplyDelete
  21. We ar e the Best Software Training Institute in Bangalore with real time examples training by real-time experts

    ReplyDelete
  22. Thanks for sharing the information,keep on updating the content. Best software Training institute in Bangalore

    ReplyDelete
  23. Thanks for sharing the useful content and would like to read this blog regularly to get more stuff from this area.
    Selenium Training in Chennai | Selenium Online Training in Chennai

    ReplyDelete
  24. Thank you for sharing information, this content is very useful to us, please share more info regularly Best Software Training in Chennai

    ReplyDelete
  25. This comment has been removed by the author.

    ReplyDelete
  26. Thanks for sharing the useful content and would like to read this blog regularly to get more stuff from this area.
    Power Bi Online Training

    ReplyDelete
  27. Thanks in favor of sharing such a nice thought, post is pleasant, thats why I have read it completely
    Informatica Online Training

    ReplyDelete
  28. Very nice write-up. I definitely appreciate this website.Keep writing!
    MSBI Training Classes

    ReplyDelete
  29. Populated with sparkling lakes and also rivers, this location of Ireland is a real boaters’ heaven
    Mysql Training Classes

    ReplyDelete
  30. This comment has been removed by the author.

    ReplyDelete
  31. Thanks in favor of sharing such a nice thought, post is pleasant,this content is very useful to us training with placement in Hyderabad

    ReplyDelete
  32. This comment has been removed by the author.

    ReplyDelete
  33. Awesome! Education is the extreme motivation that open the new doors of data and material. So we always need to study around the things and the new part of educations with that we are not mindful.
    Selenium online training

    ReplyDelete
  34. This software of QuickBooks comes with various versions and sub versions. Online Payroll and Payroll for Desktop may be the two major versions and they're further bifurcated into sub versions. Enhanced Payroll and Full-service payroll are encompassed in Online Payroll whereas Basic, QuickBooks Payroll Support Phone Number

    ReplyDelete
  35. QuickBooks Support Number also extends to those errors when QB Premier is infected by a virus or a spyware. We also handle any type of technical & functional issue faced during installation of drivers for QuickBooks Premier Version. We also troubleshoot any kind of error which might be encountered in this version or this version in a multi-user mode.

    ReplyDelete
  36. We're going to also provide you with the figure of your respective budget which you can be in the near future from now. This is only possible with QuickBook Support

    ReplyDelete
  37. Really you have done great job,There are may person searching about that now they will find enough resources by your post

    Tableau online training

    ReplyDelete
  38. QuickBooks Tech Support Phone Number have a team of experts that might be pro in handling the majority of the issues this is why incredible software.

    ReplyDelete
  39. QuickBooks Enterprise offers useful features which makes it more reliable as well as efficient. You can easily run your online business smoothly with great ease and flexibility utilizing this specialized accounting software. This is how you can save your valued time & money using intuit enterprise support. If you're a QuickBooks user and facing any issue regarding this software then call on the QuickBooks Enterprise Support Number USA.

    ReplyDelete
  40. Though QuickBooks 24/7 Payroll Support Phone Number USA a helpful tool for QuickBooks users in the business realm, yet some hits and misses may arise anytime during use. All of these issues become a good inconvenience to users causing a group back again to the highly reputed nature of QuickBooks accounting software.

    ReplyDelete
  41. By using QuickBooks Desktop Payroll Support Phone Number, you're able to create employee payment on time. However in any case, you might be facing some problem when making use of QuickBooks payroll such as for instance issue during installation, data integration error, direct deposit issue, file taxes, and paychecks errors, installation or up-gradation or simply just about some other than you don’t panic, we provide quality QuickBooks Payroll help service. Here are some features handle by our QB online payroll service.

    ReplyDelete
  42. At QuickBooks Customer Technical Support Number we work with the principle of consumer satisfaction and our effort is directed to give you a transparent and customer delight experience. A timely resolution into the minimum span could be the targets of QuickBooks Toll-Free Pro-Advisors.

    ReplyDelete

  43. QuickBooks Tech Support Phone Number users in many cases are found in situations where they have to face most of the performance plus some other errors as a consequence of various causes of their computer system.

    ReplyDelete
  44. QuickBooks Customer Support Number – The core strength of each business, be it a start-up or the biggest Multi-national firms is its accounting and management. it is thought of to be one among the foremost tedious and tough tasks to manage the Payroll of the workers, making Invoices chase sales.

    ReplyDelete
  45. If any method or technology you can not understand, if that's the case your better option is which will make call us at our QuickBooks Payroll Tech Support Number platform.

    ReplyDelete
  46. To obtain a mistake free accounting experience, our QuickBooks Enterprise Support Phone Number team is here to permit you focus on your organization development in place of troubleshooting the accounting errors.

    ReplyDelete
  47. QuickBooks Help & Support make sure that the solutions we give you would be best ideal for your software, both for the current situation and for future. Regardless of leveraging you with less time-consuming answers, we never compromise with the quality of your services.

    ReplyDelete
  48. Our dedicated team is sure to you. They've been surely working twenty-four hours a day to aid and guide you if you come across any QuickBooks Tech Support Number Our QuickBooks Support team surely have in-depth knowledge concerning the problems and issues of QuickBooks.

    ReplyDelete
  49. This comment has been removed by the author.

    ReplyDelete
  50. These workout sessions are to ensure that the QuickBooks Tech Support Phone Number team is fully prepared and able to handle all sort of technical and functional issues.

    ReplyDelete
  51. It’s extraordinary for organizations which report using one basis & record assesses an additional.Search into the chart of accounts is very simple to control with added search bar right into the chart of accounts. For better information, you can call at Intuit Enterprise Support Phone Number.

    ReplyDelete
  52. The above mentioned solutions must be sufficient in solving the QuickBooks Error Code 6000-301 and restoring your workflow. If you wish to know or are confused on some of the above-provided info, you should talk to a technical expert at QuickBooks Desktop support telephone number.

    ReplyDelete
  53. QuickBooks Support Phone Number

    Quick books Support Phone Number +1-888-422-3444.
    Quick Books accounting software is the best accounting software commonly abbreviated by the name QB used to manage and organize all finance-related information properly. Reliability, accuracy, and certainly increase its demand among businessmen and entrepreneurs. It is an amazing money management system for numerous companies around the world.


    ReplyDelete
  54. This comment has been removed by the author.

    ReplyDelete
  55. QuickBooks Support Phone Number The bond lost issue, connection with the free web, sync issue in the software along with other style of setting which not easily can be located & may block the entire workflow .

    ReplyDelete
  56. lexmark Printer Support Phone Number

    Lexmark printers are considered among the most popular printers all over the world. The company has gained millions of users worldwide because of the attractive features and impressive printing quality. Lexmark Printer Support Number
    Checkout the Lexmark Printer support number to get resolution of any Problem Related to Lexmark Printer. We are always available for your Support 365 days. If yes, you're in the right place, get one-stop solutions for all sorts of Lexmark printer issues and get them resolved within no time just by contacting Lexmark printer customer support toll-free number +1-888-600-5222.

    ReplyDelete
  57. Entering your details each time you make any transaction takes some time as well as opens windows of committing mistake specially while you are in hurry and thus this amazing property of QuickBooks Tech Support Number helps for making your projects easy.

    ReplyDelete
  58. Our 247 Tech Support Number are terribly dedicated and might solve your entire issues without the fuss. In the event that you call, you are greeted by our client service representative when taking all of your concern he/she will transfer your preference into the involved department. The best part is the fact that not just you’ll prepare you to ultimately resolve your problems nevertheless you are often acquiesced by our technicians and he/she could well keep updating you concerning your problems. it's likely you have a whole information what the problem your package is facing.

    ReplyDelete
  59. Such as for example simply fixing your damaged QuickBooks company file by using QuickBooks Enterprise Support Phone Number file doctor tool. And simply fix QuickBooks installation errors or issues with the use of wonderful QuickBooks install diagnostic tool.

    ReplyDelete

  60. More often than not when people are protesting about incorrect calculation and defaults paychecks results. Similarly fixing QuickBooks Payroll Tech Support Number of account can also be a confusing strive to do and hard to handle all of these for a common user.

    ReplyDelete
  61. We've got experienced people to give you the figure. We are going to also provide you with the figure within your budget which you are able to get in the future from now. This will be only possible with QuickBooks Support Phone Number.

    ReplyDelete
  62. In conclusion, don’t hesitate to call us on our QuickBooks Online Help Number. We have been surely here for you personally. In conclusion, any error, any problem, any bug or whatever else pertaining to QuickBooks Customer Service related problem, just call our QuickBooks Tech Support Number.

    ReplyDelete

  63. Thanks for post ing such an useful and informative stuff.SVR Technologies is the best online training institute for Selenium Online Training and we also offer self learning on Selenium Tutorials which will be very helpful for Selenium Tutorial for Beginner . Thanks for posting...

    ReplyDelete
  64. Your blog provided us with valuable information to work with. Each & every tips of your post are awesome. Thanks a lot for sharing.
    AWS training in chennai | AWS training in anna nagar | AWS training in omr | AWS training in porur | AWS training in tambaram | AWS training in velachery

    ReplyDelete
  65. great post!!Thanks for your informative article, Your post helped me to understand the future and career prospects & Keep on updating your blog with such awesome article.

    Android Training in Chennai

    Android Online Training in Chennai

    Android Training in Bangalore

    Android Training in Hyderabad

    Android Training in Coimbatore

    Android Training

    Android Online Training

    ReplyDelete
  66. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...data science courses

    ReplyDelete
  67. Wonderful blog. I delighted in perusing your articles. This is genuinely an incredible perused for me. I have bookmarked it and I am anticipating perusing new articles. Keep doing awesome!
    data scientist training and placement in hyderabad

    ReplyDelete
  68. Great post I must say and thanks for the information. Education is definitely a sticky subject. However, is still among the leading topics of our time. I appreciate your post and look forward to more. 4 ps of marketing

    ReplyDelete

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives