“Program to an interface, not an implementation” they[1] say …
But when IMyInterface foo = new IMyInterface() is not valid code … how are you supposed to achieve that ? The answer is Dependency Injection.
In this talk, we’ll talk about Dependency injection, what it is and what it is not. We’ll see how it is a valuable set of practices and patterns that help design maintainable software built on top of the SOLID object-oriented principles.
We’ll see how, when used properly, it delivers many benefits such as extensibility and testability … We’ll also cover some anti-patterns, ways of using Dependency Injection that can lead to code that is painful to understand and maintain
This talk is not about DI/IOC containers per se, but focuses on the core concepts of Dependency Injection. Those concepts are essential to understand how to use those “magic-looking” tools (if they are needed at all …)
This talk is not only for .NET developers. It will contain code examples written in C#, but should be understandable by developers with knowledge in other statically-typed object-oriented languages such as Java, Vb.NET, C++ …
What is Dependency Injection in Spring Boot | EdurekaEdureka!
YouTube Link: https://youtu.be/O9mqe53syGc
** Microservices Architecture Training: https://www.edureka.co/microservices-... **
This Edureka tutorial on "What is Dependency Injection" will give you an introduction to dependency injection and also show a practical implementation of dependency injection with Spring Boot.
In this PPT, you will learn the following:
What is Dependency Injection?
Inversion of Control
Types of Dependency Injection
Benefits of Dependency Injection
Implement Dependency Injection using Spring Boot
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Castbox: https://castbox.fm/networks/505?country=in
Information about the Coupling, it's type and how to achieve Loose Coupling, Dependency injection principles (DI, IOC) and different Dependency Inversion Containers and DI Pros and Cons
What is Dependency Injection in Spring Boot | EdurekaEdureka!
YouTube Link: https://youtu.be/O9mqe53syGc
** Microservices Architecture Training: https://www.edureka.co/microservices-... **
This Edureka tutorial on "What is Dependency Injection" will give you an introduction to dependency injection and also show a practical implementation of dependency injection with Spring Boot.
In this PPT, you will learn the following:
What is Dependency Injection?
Inversion of Control
Types of Dependency Injection
Benefits of Dependency Injection
Implement Dependency Injection using Spring Boot
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Castbox: https://castbox.fm/networks/505?country=in
Information about the Coupling, it's type and how to achieve Loose Coupling, Dependency injection principles (DI, IOC) and different Dependency Inversion Containers and DI Pros and Cons
Presentation explain about
Spring Boot vs Spring vs Spring MVC,
Advantages,
Where to start and how does Spring boot work ?,
Dependency Management,
Logging,
Exception Handling,
Database Handling.
in Spring boot.
slides contains all about the ASP.NET MVC 5 based contents, and hopefully this will also guide you how to a write the MVC program using .NET Technology
This document is about how to Write a CRUD App with Spring Boot Jpa or jdbc. a related example for this document is on github with the following address :
https://github.com/ghorbanihamid/SpringBoot_AOP_JPA_Example
Modern Java web applications with Spring Boot and ThymeleafLAY Leangsros
If you’re using Java in an enterprise environment, you’ve most likely been using Spring Framework with JSP which does the job pretty well.But I will provide the sampling of how Spring Boot helps you accelerate and facilitate application development better. I will show a templating technology, Thymleaf which can be used much more modern features;
SOLID Principles and The Clean ArchitectureMohamed Galal
This presentation is held at @blablaconnect Cairo office, Monday 31 December 2018.
In this presentation we will discuss the following topics:
- SOLID principles.
- Design Pattern vs. Clean Architecture.
- Successful software architecture characteristics.
- The Clean Architecture.
- Real life example.
In this Java Spring Training session, you will learn Spring – Inversion of Control, Dependency Injection and Bean definitions. Topics covered in this session are:
For more information, visit this link:
Spring Framework
• Core Container
• Data Access/Integration
• Web Layer
• Spring Setup
• Key features
• Spring Bean
• Dependency Injection
• Relation between DI and IoC
• Spring IoC Containers
• Spring DI
https://www.mindsmapped.com/courses/software-development/spring-fundamentals-learn-spring-framework-and-spring-boot/
This presentation goes through what Inversion of Control is, which IOC patterns that exists, which of the patterns you should use and when you should use them.
Presentation explain about
Spring Boot vs Spring vs Spring MVC,
Advantages,
Where to start and how does Spring boot work ?,
Dependency Management,
Logging,
Exception Handling,
Database Handling.
in Spring boot.
slides contains all about the ASP.NET MVC 5 based contents, and hopefully this will also guide you how to a write the MVC program using .NET Technology
This document is about how to Write a CRUD App with Spring Boot Jpa or jdbc. a related example for this document is on github with the following address :
https://github.com/ghorbanihamid/SpringBoot_AOP_JPA_Example
Modern Java web applications with Spring Boot and ThymeleafLAY Leangsros
If you’re using Java in an enterprise environment, you’ve most likely been using Spring Framework with JSP which does the job pretty well.But I will provide the sampling of how Spring Boot helps you accelerate and facilitate application development better. I will show a templating technology, Thymleaf which can be used much more modern features;
SOLID Principles and The Clean ArchitectureMohamed Galal
This presentation is held at @blablaconnect Cairo office, Monday 31 December 2018.
In this presentation we will discuss the following topics:
- SOLID principles.
- Design Pattern vs. Clean Architecture.
- Successful software architecture characteristics.
- The Clean Architecture.
- Real life example.
In this Java Spring Training session, you will learn Spring – Inversion of Control, Dependency Injection and Bean definitions. Topics covered in this session are:
For more information, visit this link:
Spring Framework
• Core Container
• Data Access/Integration
• Web Layer
• Spring Setup
• Key features
• Spring Bean
• Dependency Injection
• Relation between DI and IoC
• Spring IoC Containers
• Spring DI
https://www.mindsmapped.com/courses/software-development/spring-fundamentals-learn-spring-framework-and-spring-boot/
This presentation goes through what Inversion of Control is, which IOC patterns that exists, which of the patterns you should use and when you should use them.
Learn how to leverage functional concepts of Partial Application and Function Composition for Dependency Injection in C#. This is to achieve Simplicity.
All 3 Clean Code presentations provide great value by themselves, but taken together are designed to offer a holistic approach to successful software creation. This first session creates the foundation for the 2nd and 3rd Clean Code presentation on Dependency Injection, as it explains expected base knowledge. Why writing Clean Code makes us more efficient Over the lifetime of a product, maintaining the product is actually one - if not the most - expensive area(s) of the overall product costs.
We will dive into the basics of Inversion of Control (IOC) and Dependency Injection (DI) to review different ways of achieving decoupling, using and exploring both: Best Practices, Design and Anti Patterns. This presentation requires knowledge and understanding of basics like DRY, SoC, SRP, SOLID etc. which are building the base for decoupled architecture. However, we will start at the basics of DI and will work towards intermediate and advanced scenarios depending on the participating group.
This presentation is based on C# and Visual Studio 2013. However, the demonstrated patterns and practice can be applied to every other programming language too.
Note: Moving forwards this presentation will be updated with the latest version of the slides for the last event I did the presentation instead of creating new separate slide decks here on SlideShare.
Presentation dates and locations:
2015-10-03 Silicon Valley Code Camp, San Jose, CA
2015-06-27 SoCal Code Camp - San Diego, CA
2015-06-25 Bay.NET South Bay, Mountain View, CA
2014-11-14 SoCal Code Camp - Los Angeles, CA
2014-10-11 Silicon Valley Code Camp, Los Altos Hills, CA
How to create loosely coupled code using Dependency Injection? What are the DI patterns and anti patterns? How to properly inject dependencies in ASP.NET MVC? What DI containers are available in .NET?
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlArjun Thakur
Hi, I just prepared a presentation on Java Spring Framework, the topics covered include architecture of Spring framework and it's modules. Spring Core is explained in detail including but not limited to Inversion of Control (IoC), Dependency Injection (DI) etc. Thank you and happy learning. :)
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...Dan Wahlin
This is a talk I gave at the spring 2013 AngleBrackets/DevIntersection conference in Las Vegas.
HTML5 is all the rage these days but where do you look to find robust examples of using it along with jQuery, client-side templates, Ajax calls, data access technologies, and more? In this session, Dan Wahlin will walk through an application that demonstrates how key HTML5 technologies can be integrated and used to present data to users in different ways. Topics covered include exposing data to the client using RESTful services created using the new ASP.NET Web API, using Handlebars templates to render data, JavaScript techniques for structuring code, the role of HTML5 semantic tags, as well as how technologies such as the canvas, SVG, and video can be used. If you want to learn server-side as well as client-side techniques and strategies then this session is for you.
Any structure expected to stand the test of time and change needs a strong foundation! Software is no exception. Engineering your code to grow in a stable and effective way is critical to your ability to rapidly meet the growing demands of users, new features, technologies, and platform capabilities. Join us to obtain architect-level design patterns for use in your Apex code to keep it well factored, easy to maintain, and in line with platform best practices. You'll follow a Force.com interpretation of Martin Fowler's Enterprise Architecture Application patterns, and the practice of Separation of Concerns.
Redux - негласный победитель Flux соревнований, одна из трендовых библиотек 2015 года. Слишком "сырой" для продакшена? Нет, мы так не думаем! Используя силу функционального подхода и модель Event Sourcing'a, Redux позволяет гибко управлять состоянием вашего приложения. В докладе мы расскажем про то, как мы, используя связку Redux+React, переписали с нуля front-end одного из наших продуктов (Лидсканер | leadscanner.ru). Рассмотрим реальные плюсы и минусы данного стека, в частности: работу с side-effects, повторное использование компонентов, тестируемость.
Структура:
Про нас.
Какие перед нами стояли вызовы.
Многоуровневая архитектура.
Обзор Flux архитектуры.
Redux - Predictable state container for JavaScript apps.
React как view layer.
Повторное использование компонентов.
Dumb and Smart components.
Feature Folders.
Работа с side effects.
Обзор подходов организации actionCreators.
Middlewares.
Redux-saga.
Минусы данного стека.
Developing ASP.NET Applications Using the Model View Controller Patterngoodfriday
Learn how to use the model-view-controller (MVC) pattern to take advantage of your favorite .NET Framework language for writing business logic in a way that is de-coupled from the views of the data.
mDT #5, 24. 11. 2016
Storing account information is a common challenge many app developers face, and is often tackled in tailored solutions. Isn’t there some strategy to store account credentials in a centralized place? What about multiple accounts, like Twitter? And when should or could I synchronize data? Android offers a powerful account manager. Let’s explore the possibilities and lay out an architecture for engineering an Android app based on accounts.
1-What are the opportunities and threats that could impact the orgAbbyWhyte974
1-What are the opportunities and threats that could impact the organization?
· Review all the general environmental categories. (PESTEL Analysis)
· Use Porter’s Five Forces model to analyze the company’s industry. Identify key competitors and analyze their strategies, core competencies, and competitive response.
2-What are the strengths or weaknesses of the organization?
· Review factors within the company that are critical to the strategy of the firm and classify them as strengths or weaknesses.
· Look for resources, capabilities, and core competencies.
· Use the "Four Criteria of Sustainable Competitive Advantage".
3-In the past, BMW has been able to successfully differentiate its products by engaging in value-adding value chain activities. What are some of these specific activities? How can BMW ensure its ability to continue with value-adding activities as it evolves into a maker of self-driving cars?
· Use the "Value Chain Analysis" to identify value-adding activities and functions.
· This question is not about Business or Corporate level strategies. focus on the functional level.
Programming Using Inheritance/Programming Using Inheritance/.vs/Programming Using Inheritance/v16/.suo
Programming Using Inheritance/Programming Using Inheritance/Account.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Programming_Using_Inheritance
{
class Account
{
//Declares the instance variable for the class
private decimal Balance;
private string AccountName;
private int AccountNumber;
//Creates the class constructor and initialize its instance variables using mutator methods
public Account(decimal Balance, string AccountName, int AccountNumber)
{
setAccontNumber(AccountNumber);
setAccountName(AccountName);
//For the balance initialization to make sure it is greater than zero
if (Balance >= 0)
setBalance(Balance);
else
setBalance(Balance);
}
//Creates mutator methods to set balance, accountNumber and accountName
public void setBalance(decimal Balance)
{
this.Balance = Balance;
}
public void setAccontNumber(int AccountNumber)
{
this.AccountNumber = AccountNumber;
}
public void setAccountName(string AccountName)
{
this.AccountName = AccountName;
}
//To get the instance field variables
public decimal getBalance()
{
return this.Balance;
}
public int getAccontNumber()
{
return this.AccountNumber;
}
public string getAccountName()
{
return this.AccountName;
}
//Creates a credit method to add current balance to passed balance ...
1-What are the opportunities and threats that could impact the orgMartineMccracken314
1-What are the opportunities and threats that could impact the organization?
· Review all the general environmental categories. (PESTEL Analysis)
· Use Porter’s Five Forces model to analyze the company’s industry. Identify key competitors and analyze their strategies, core competencies, and competitive response.
2-What are the strengths or weaknesses of the organization?
· Review factors within the company that are critical to the strategy of the firm and classify them as strengths or weaknesses.
· Look for resources, capabilities, and core competencies.
· Use the "Four Criteria of Sustainable Competitive Advantage".
3-In the past, BMW has been able to successfully differentiate its products by engaging in value-adding value chain activities. What are some of these specific activities? How can BMW ensure its ability to continue with value-adding activities as it evolves into a maker of self-driving cars?
· Use the "Value Chain Analysis" to identify value-adding activities and functions.
· This question is not about Business or Corporate level strategies. focus on the functional level.
Programming Using Inheritance/Programming Using Inheritance/.vs/Programming Using Inheritance/v16/.suo
Programming Using Inheritance/Programming Using Inheritance/Account.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Programming_Using_Inheritance
{
class Account
{
//Declares the instance variable for the class
private decimal Balance;
private string AccountName;
private int AccountNumber;
//Creates the class constructor and initialize its instance variables using mutator methods
public Account(decimal Balance, string AccountName, int AccountNumber)
{
setAccontNumber(AccountNumber);
setAccountName(AccountName);
//For the balance initialization to make sure it is greater than zero
if (Balance >= 0)
setBalance(Balance);
else
setBalance(Balance);
}
//Creates mutator methods to set balance, accountNumber and accountName
public void setBalance(decimal Balance)
{
this.Balance = Balance;
}
public void setAccontNumber(int AccountNumber)
{
this.AccountNumber = AccountNumber;
}
public void setAccountName(string AccountName)
{
this.AccountName = AccountName;
}
//To get the instance field variables
public decimal getBalance()
{
return this.Balance;
}
public int getAccontNumber()
{
return this.AccountNumber;
}
public string getAccountName()
{
return this.AccountName;
}
//Creates a credit method to add current balance to passed balance ...
Quarkus Hidden and Forbidden ExtensionsMax Andersen
Quarkus has a vast extension ecosystem and is known for its subsonic and subatomic feature set. Some of these features are not as well known, and some extensions are less talked about, but that does not make them less interesting - quite the opposite.
Come join this talk to see some tips and tricks for using Quarkus and some of the lesser known features, extensions and development techniques.
Artificia Intellicence and XPath Extension FunctionsOctavian Nadolu
The purpose of this presentation is to provide an overview of how you can use AI from XSLT, XQuery, Schematron, or XML Refactoring operations, the potential benefits of using AI, and some of the challenges we face.
GraphSummit Paris - The art of the possible with Graph TechnologyNeo4j
Sudhir Hasbe, Chief Product Officer, Neo4j
Join us as we explore breakthrough innovations enabled by interconnected data and AI. Discover firsthand how organizations use relationships in data to uncover contextual insights and solve our most pressing challenges – from optimizing supply chains, detecting fraud, and improving customer experiences to accelerating drug discoveries.
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeAftab Hussain
Understanding variable roles in code has been found to be helpful by students
in learning programming -- could variable roles help deep neural models in
performing coding tasks? We do an exploratory study.
- These are slides of the talk given at InteNSE'23: The 1st International Workshop on Interpretability and Robustness in Neural Software Engineering, co-located with the 45th International Conference on Software Engineering, ICSE 2023, Melbourne Australia
May Marketo Masterclass, London MUG May 22 2024.pdfAdele Miller
Can't make Adobe Summit in Vegas? No sweat because the EMEA Marketo Engage Champions are coming to London to share their Summit sessions, insights and more!
This is a MUG with a twist you don't want to miss.
Graspan: A Big Data System for Big Code AnalysisAftab Hussain
We built a disk-based parallel graph system, Graspan, that uses a novel edge-pair centric computation model to compute dynamic transitive closures on very large program graphs.
We implement context-sensitive pointer/alias and dataflow analyses on Graspan. An evaluation of these analyses on large codebases such as Linux shows that their Graspan implementations scale to millions of lines of code and are much simpler than their original implementations.
These analyses were used to augment the existing checkers; these augmented checkers found 132 new NULL pointer bugs and 1308 unnecessary NULL tests in Linux 4.4.0-rc5, PostgreSQL 8.3.9, and Apache httpd 2.2.18.
- Accepted in ASPLOS ‘17, Xi’an, China.
- Featured in the tutorial, Systemized Program Analyses: A Big Data Perspective on Static Analysis Scalability, ASPLOS ‘17.
- Invited for presentation at SoCal PLS ‘16.
- Invited for poster presentation at PLDI SRC ‘16.
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Łukasz Chruściel
No one wants their application to drag like a car stuck in the slow lane! Yet it’s all too common to encounter bumpy, pothole-filled solutions that slow the speed of any application. Symfony apps are not an exception.
In this talk, I will take you for a spin around the performance racetrack. We’ll explore common pitfalls - those hidden potholes on your application that can cause unexpected slowdowns. Learn how to spot these performance bumps early, and more importantly, how to navigate around them to keep your application running at top speed.
We will focus in particular on tuning your engine at the application level, making the right adjustments to ensure that your system responds like a well-oiled, high-performance race car.
AI Genie Review: World’s First Open AI WordPress Website CreatorGoogle
AI Genie Review: World’s First Open AI WordPress Website Creator
👉👉 Click Here To Get More Info 👇👇
https://sumonreview.com/ai-genie-review
AI Genie Review: Key Features
✅Creates Limitless Real-Time Unique Content, auto-publishing Posts, Pages & Images directly from Chat GPT & Open AI on WordPress in any Niche
✅First & Only Google Bard Approved Software That Publishes 100% Original, SEO Friendly Content using Open AI
✅Publish Automated Posts and Pages using AI Genie directly on Your website
✅50 DFY Websites Included Without Adding Any Images, Content Or Doing Anything Yourself
✅Integrated Chat GPT Bot gives Instant Answers on Your Website to Visitors
✅Just Enter the title, and your Content for Pages and Posts will be ready on your website
✅Automatically insert visually appealing images into posts based on keywords and titles.
✅Choose the temperature of the content and control its randomness.
✅Control the length of the content to be generated.
✅Never Worry About Paying Huge Money Monthly To Top Content Creation Platforms
✅100% Easy-to-Use, Newbie-Friendly Technology
✅30-Days Money-Back Guarantee
See My Other Reviews Article:
(1) TubeTrivia AI Review: https://sumonreview.com/tubetrivia-ai-review
(2) SocioWave Review: https://sumonreview.com/sociowave-review
(3) AI Partner & Profit Review: https://sumonreview.com/ai-partner-profit-review
(4) AI Ebook Suite Review: https://sumonreview.com/ai-ebook-suite-review
#AIGenieApp #AIGenieBonus #AIGenieBonuses #AIGenieDemo #AIGenieDownload #AIGenieLegit #AIGenieLiveDemo #AIGenieOTO #AIGeniePreview #AIGenieReview #AIGenieReviewandBonus #AIGenieScamorLegit #AIGenieSoftware #AIGenieUpgrades #AIGenieUpsells #HowDoesAlGenie #HowtoBuyAIGenie #HowtoMakeMoneywithAIGenie #MakeMoneyOnline #MakeMoneywithAIGenie
OpenMetadata Community Meeting - 5th June 2024OpenMetadata
The OpenMetadata Community Meeting was held on June 5th, 2024. In this meeting, we discussed about the data quality capabilities that are integrated with the Incident Manager, providing a complete solution to handle your data observability needs. Watch the end-to-end demo of the data quality features.
* How to run your own data quality framework
* What is the performance impact of running data quality frameworks
* How to run the test cases in your own ETL pipelines
* How the Incident Manager is integrated
* Get notified with alerts when test cases fail
Watch the meeting recording here - https://www.youtube.com/watch?v=UbNOje0kf6E
Zoom is a comprehensive platform designed to connect individuals and teams efficiently. With its user-friendly interface and powerful features, Zoom has become a go-to solution for virtual communication and collaboration. It offers a range of tools, including virtual meetings, team chat, VoIP phone systems, online whiteboards, and AI companions, to streamline workflows and enhance productivity.
Launch Your Streaming Platforms in MinutesRoshan Dwivedi
The claim of launching a streaming platform in minutes might be a bit of an exaggeration, but there are services that can significantly streamline the process. Here's a breakdown:
Pros of Speedy Streaming Platform Launch Services:
No coding required: These services often use drag-and-drop interfaces or pre-built templates, eliminating the need for programming knowledge.
Faster setup: Compared to building from scratch, these platforms can get you up and running much quicker.
All-in-one solutions: Many services offer features like content management systems (CMS), video players, and monetization tools, reducing the need for multiple integrations.
Things to Consider:
Limited customization: These platforms may offer less flexibility in design and functionality compared to custom-built solutions.
Scalability: As your audience grows, you might need to upgrade to a more robust platform or encounter limitations with the "quick launch" option.
Features: Carefully evaluate which features are included and if they meet your specific needs (e.g., live streaming, subscription options).
Examples of Services for Launching Streaming Platforms:
Muvi [muvi com]
Uscreen [usencreen tv]
Alternatives to Consider:
Existing Streaming platforms: Platforms like YouTube or Twitch might be suitable for basic streaming needs, though monetization options might be limited.
Custom Development: While more time-consuming, custom development offers the most control and flexibility for your platform.
Overall, launching a streaming platform in minutes might not be entirely realistic, but these services can significantly speed up the process compared to building from scratch. Carefully consider your needs and budget when choosing the best option for you.
Mobile App Development Company In Noida | Drona InfotechDrona Infotech
Looking for a reliable mobile app development company in Noida? Look no further than Drona Infotech. We specialize in creating customized apps for your business needs.
Visit Us For : https://www.dronainfotech.com/mobile-application-development/
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Crescat
Crescat is industry-trusted event management software, built by event professionals for event professionals. Founded in 2017, we have three key products tailored for the live event industry.
Crescat Event for concert promoters and event agencies. Crescat Venue for music venues, conference centers, wedding venues, concert halls and more. And Crescat Festival for festivals, conferences and complex events.
With a wide range of popular features such as event scheduling, shift management, volunteer and crew coordination, artist booking and much more, Crescat is designed for customisation and ease-of-use.
Over 125,000 events have been planned in Crescat and with hundreds of customers of all shapes and sizes, from boutique event agencies through to international concert promoters, Crescat is rigged for success. What's more, we highly value feedback from our users and we are constantly improving our software with updates, new features and improvements.
If you plan events, run a venue or produce festivals and you're looking for ways to make your life easier, then we have a solution for you. Try our software for free or schedule a no-obligation demo with one of our product specialists today at crescat.io
Enterprise Resource Planning System includes various modules that reduce any business's workload. Additionally, it organizes the workflows, which drives towards enhancing productivity. Here are a detailed explanation of the ERP modules. Going through the points will help you understand how the software is changing the work dynamics.
To know more details here: https://blogs.nyggs.com/nyggs/enterprise-resource-planning-erp-system-modules/
E-commerce Application Development Company.pdfHornet Dynamics
Your business can reach new heights with our assistance as we design solutions that are specifically appropriate for your goals and vision. Our eCommerce application solutions can digitally coordinate all retail operations processes to meet the demands of the marketplace while maintaining business continuity.
3. This talk
• What it is about
– Dependency Injection (DI) patterns
– Benefits
– Common pitfalls
• What it is not about
– Specific IoC/DI Container implementations
• Pre-requisites
– OOP
– Class-based statically-typed languages
• Based on examples
7. Dependency Injection
Dependency Injection is a set of practices that
allow to build loosely coupled applications
It’s NOT :
– A library
– A framework
– A tool
It IS :
- A way of thinking
- A way of designing code
- General guidelines
8. Dependency Injection
Dependency Injection is a set of practices that
allow to build loosely coupled applications
Small components …
- Independent
- Reusable
- Interchangeable
… plugged together to
form a bigger system
Benefits :
- Small classes with single
responsibility
- Easier maintenance
- Extensibility
- Testable
9. Show me the code !
FROM TIGHTLY TO LOOSELY
COUPLED
10. Example : Boring Bank™ System
• Features
– User can list his
accounts
– User can rename his
accounts
– User can transfer money
from an account to the
other
• Tech :
– Web front-end
– Relational database
11. Starting from scratch
public class AccountController : BaseController
{
// GET: Account
[HttpGet]
public ActionResult Index()
{
var userId = this.User.AsClaimsPrincipal().UserId();
using (var context = new BankingDbContext())
{
var accounts = context.Accounts
.Where(a => a.CustomerId == userId)
.OrderBy(a => a.Title).ToList();
return View(accounts);
}
}
[HttpPost]
public ActionResult TransferPost(int from, int to, decimal amount)
{
var userId = this.User.AsClaimsPrincipal().UserId();
using (var context = new BankingDbContext())
{
var accountFrom = context.Accounts
.Single(a => a.CustomerId == userId && a.Id == from);
var accountTo = context.Accounts
.Single(a => a.CustomerId == userId && a.Id == to);
accountFrom.Balance -= amount;
accountTo.Balance += amount;
context.SaveChanges();
return RedirectToAction("Index");
}
}
data
business
presentation
12. Tightly-coupled code
• Using another kind of UI ?
• Using another kind of storage ?
• Using the business rules somewhere else ?
14. public class AccountController : BaseController
public Account GetAccountForCustomer(int customerId, int accountId)
{
// GET: Account
[HttpGet]
public ActionResult Index()
{
var userId = this.User.AsClaimsPrincipal().UserId();
public void Transfer(int userId, int fromAccountId, int toAccountId, decimal amountToTransfer
var userAccountService = new UserAccountService();
var accounts = userAccountService.GetAccountsForCustomer(userId);
return View(ToViewModel(accounts));
}
[HttpPost]
public ActionResult TransferPost(int from, int to, decimal amount)
{
var userId = this.User.AsClaimsPrincipal().UserId();
var userAccountService = new UserAccountService();
userAccountService.Transfer(userId, from, to, amount);
return RedirectToAction("Index");
}
AccountController.cs (WebPortal)
UI talks to Business
{
// TODO : validate arguments
var accountRepository = new AccountRepository();
var fromAccount = accountRepository.GetAccountForCustomer(userId, fromAccountId);
var toAccount = accountRepository.GetAccountForCustomer(userId, toAccountId);
// TODO : verify that there is enough money
fromAccount.Balance -= amountToTransfer;
toAccount.Balance += amountToTransfer;
accountRepository.Update(fromAccount);
accountRepository.Update(toAccount);
}
UserAccountService.cs (Business)
Business talks to Data
{
using (var context = new BankingDbContext("BankingDbContext"))
{
var account = context.Accounts
.Single(a => a.CustomerId == customerId && a.Id == accountId);
return account;
}
}
public void Update(Account account)
{
using (var context = new BankingDbContext("BankingDbContext"))
{
var accountEf = context.Accounts.Find(account.Id);
// theoretically, could do "if not changed"
accountEf.Balance = account.Balance;
accountEf.Title = account.Title;
context.SaveChanges();
}
}
AccountRepository.cs (Data)
16. anti-pattern : Control Freak
• Symptoms:
– Code insists on how the dependencies are built
– Makes it impossible to use component in isolation
– Not testable without full stack
• Easy to spot : new everywhere
AccountController : BaseController
Account
HttpGet]
ActionResult Index()
userId = this.User.AsClaimsPrincipal().UserId();
userAccountService = new UserAccountService();
accounts = userAccountService.GetAccountsForCustomer(userId);
return View(ToViewModel(accounts));
public void Transfer(int userId, int fromAccountId, int toAccountId
{
// TODO : validate arguments
var accountRepository = new AccountRepository();
var fromAccount = accountRepository.GetAccountForCustomer
var toAccount = accountRepository.GetAccountForCustomer
// TODO : verify that there is enough money
fromAccount.Balance -= amountToTransfer;
toAccount.Balance += amountToTransfer;
accountRepository.Update(fromAccount);
accountRepository.Update(toAccount);
}
17. Unit tests as a Coupling Detector
• Unit tests are “just another client” for your
code
• If unit tests are hard to write, the code is
probably too tightly coupled
-> Let’s make it testable !
18. Making it testable - Properties
public class UserAccountService
{
[TestMethod]
public void RenameAccount_must_UpdateAccountName()
{
public UserAccountService()
{
AccountRepository = new AccountRepository("BankingContext");
}
#region Dependency Management
public AccountRepository AccountRepository { get; set; }
#endregion
Settable property allows
to “inject” another instance
// Arrange
var newName = "someName";
var existingAccount = AnAccount();
var sut = new UserAccountService();
sut.AccountRepository = FAIL FAIL//I want to put a fake here !
// Act
sut.RenameAccount(existingAccount.CustomerId, existingAccount.Id,
newName);
// Assert
// I want to verify what happened ..
}
In UserAccountServiceTest.cs , in test project Business.Tests
19. Programming to an interface
public class UserAccountService : IUserAccountService
[TestMethod]
{
public void RenameAccount_must_UpdateAccountName()
{
public UserAccountService()
{
// Arrange
var newName = "someName";
AccountRepository = new AccountRepository("BankingContext");
}
var existingAccount = AnAccount();
#region Dependency Management
var mockRepo = new Mock<IAccountRepository>();
mockRepo.Setup(r => r.GetAccountForCustomer(It.IsAny<int>(), It.IsAny<int>()))
public IAccountRepository AccountRepository { get; set; }
.Returns(existingAccount);
var sut = new UserAccountService();
sut.AccountRepository = mockRepo.Object; //I want to put a fake here !
#endregion Use an interface (or abstract class) instead of concrete class
// Act
sut.RenameAccount(existingAccount.CustomerId, existingAccount.Id, newName);
// Assert
mockRepo.Verify(r=> r.Update(It.Is<Data.Account>(a=> a.Title == newName)));
}
Inject fake instance
20. pattern : Property Injection
Expose settable properties to modify dependencies
Benefits
• Useful to provide optional extensibility
• There must be a good “local default” implementation
Caveats
• Not very easy to discover point of extension
• Easy to forget
• Extra care to avoid NullReferenceExceptions, handle
thread-safety etc
21. Making it more explicit - Constructor
public class UserAccountService : IUserAccountService
{
private readonly IAccountRepository _accountRepository;
Injection constructor
used in tests - declare required dependencies as constructor parameters
public UserAccountService(IAccountRepository accountRepository)
{
public IAccountRepository AccountRepository { get { return _accountRepository; if (accountRepository == null) throw new ArgumentNullException("accountRepository
_accountRepository = accountRepository;
}
public UserAccountService()
:this(new AccountRepository("BankingContext"))
{
}
#region Dependency Management
Default constructor
used in production code
[TestMethod]
public void RenameAccount_must_UpdateAccountName()
{
// Arrange
var newName = "someName";
var existingAccount = AnAccount();
var mockRepo = new Mock<IAccountRepository>();
mockRepo.Setup(r => r.GetAccountForCustomer(It.IsAny<int>(), It.IsAny<int>()))
.Returns(existingAccount);
var sut = new UserAccountService(mockRepo.Object);
// Act
sut.RenameAccount(existingAccount.CustomerId, existingAccount.Id, newName);
// Assert
mockRepo.Verify(r=> r.Update(It.Is<Data.Account>(a=> a.Title == newName)));
}
Inject fake instance
22. anti-pattern : Bastard Injection
Enable dependencies for testing, but use hard-code
implementation in production code
• Paradox:
– Lots of efforts to reduce coupling
– … but forcing a hard-coded value
• Test-specific code
• Ambiguity
23. Cutting the dependency chain
public class AccountController : BaseController
{
private readonly IUserAccountService _userAccountService;
public class UserAccountService : IUserAccountService
Only 1 constructor - dependencies passed as constructor arguments
{
public private AccountController(readonly IAccountRepository IUserAccountService _accountRepository;
userAccountService)
{
if (userAccountService == null) throw new ArgumentNullException("userAccountService
_userAccountService = userAccountService;
}
public UserAccountService(IAccountRepository accountRepository)
{
if (accountRepository == null) throw new ArgumentNullException("accountRepository
_accountRepository = accountRepository;
AccountController (WebPortal)
}
UserAccountService.cs (Business)
24. pattern : Constructor Injection
Declare required dependencies as constructor
parameters
• Declarative
• Discoverable (Intellisense, Reflection …)
• Recommended approach in 99.9% of cases
• Easy to implement
Need Guard clause because C# does not support non-nullable
reference types …
26. This is great and everything except …
[InvalidOperationException: An error occurred when trying to create a controller of 'BoringBank.WebPortal.Controllers.AccountController'. Make sure that the controller System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext
27. The chicken and the egg
IAccountRepository repo = new IAccountRepository();
• Ideal world: Programming to interfaces
vs
• Real world : applications do not work with only
interfaces
• Class instances have to be created and assembled
(=composed) at some point
• This happens only in one place in an application
28. pattern : Composition Root
Composition of classes into a larger system should
happen only in one place
• Create one object-graph
• As late as possible
• Only part of the code that can reference concrete types
Where ?
• Only applications have a Composition Root
• There is no Composition Root in a class library
• Extension point depends on the kind of app
29. ASP.NET MVC Composition Root
public class AppCompositionRoot : DefaultControllerFactory
• IControllerFactory
• Creates a controller instance based on URL
• DefaultControllerFactory uses default
constructor on Controller
• … but it can be changed !
{
protected override IController GetControllerInstance(RequestContext requestContext
Type controllerType)
{
// how to compose an AccountController ?
if (controllerType == typeof(AccountController))
{
var connectionString = ConfigurationManager
.ConnectionStrings["BankingDbContext"].ConnectionString;
var repo = new AccountRepository(connectionString);
var service = new UserAccountService(repo);
return new AccountController(service);
Controller
composition
}
// standard way in MVC to use default strategy
return base.GetControllerInstance(requestContext, controllerType);
}
}
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
var factory = new AppCompositionRoot();
ControllerBuilder.Current.SetControllerFactory(factory);
In Global.asax
tell MVC to use our composition root
30. Pure DI (aka Poor Man’s DI)
Manual wiring of dependencies
• Very explicit (no « magic »)
• Type-safe
• … but repetitive and boring
var connectionString = ConfigurationManager
.ConnectionStrings["BankingDbContext"].ConnectionString;
var repo = new AccountRepository(connectionString);
var service = new UserAccountService(repo);
return new AccountController(service);
34. Extensibility
public class CachedAccountRepository : IAccountRepository
{
private readonly ICache _cache;
private readonly IAccountRepository _decorated;
• Decorator Pattern
public CachedAccountRepository(ICache cache, IAccountRepository decorated)
{
– Very DI-friendly pattern
var nakedRepo = new AccountRepository(connectionString);
if (cache == null) throw new ArgumentNullException("cache");
if (decorated == null) throw new ArgumentNullException("decorated");
_cache = cache;
_decorated = decorated;
// decorate the nakedRepository with caching features
var • Example longCache = : new caching
DotNetCache(TimeSpan.FromHours(1));
var cachedRepo = new CachedAccountRepository(longCache, nakedRepo);
var service }
= new UserAccountService(cachedRepo);
public IReadOnlyList<Account> GetAccountsForCustomer(int userId)
{
var accounts = _cache.GetOrAdd("accounts_" + userId,
() => _decorated.GetAccountsForCustomer(userId));
return accounts;
}
Decorator
delegate to decorated instance
36. DI Container – how they work
• Mapping Abstraction-> Concrete Type
– Usually initialized on app start
– Methods like
Register<IAbstraction,ConcreteType>()
• Method Resolve<TRequired>()
• Recursively resolves dependencies reading
constructor parameters
37. public class DependencyConfig
Example - Unity
{
public static void Configure(IUnityContainer container)
{
var connectionString = ConfigurationManager.ConnectionStrings["BankingDbContext"
public class MvcApplication : System.Web.HttpApplication
{
public class AppCompositionRoot : DefaultControllerFactory
protected void Application_Start()
{
private readonly IUnityContainer _unityContainer;
var container = new UnityContainer();
DependencyConfig.Configure(container);
var compositionRoot = new AppCompositionRoot(container);
ControllerBuilder.Current.SetControllerFactory(compositionRoot
{
In Global.asax
.ConnectionString;
container.RegisterType<IAccountRepository, AccountRepository>(
new InjectionConstructor(connectionString));
container.RegisterType<IUserAccountService, UserAccountService>();
}
}
public AppCompositionRoot(IUnityContainer unityContainer)
{
In DependencyConfig
if (unityContainer == null) throw new ArgumentNullException("unityContainer
_unityContainer = unityContainer;
}
protected override IController GetControllerInstance(RequestContext requestContext
controllerType)
{
return (IController) _unityContainer.Resolve(controllerType);
}
}
In CompositionRoot
Register / Resolve (/ Release)
38. Aspects of DI
• Composition
• Lifetime Management
• Interception
40. public class TimingBehavior : IInterceptionBehavior
{
public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext
{
var stopwatch = new Stopwatch();
// Before invoking the method on the original target.
Debug.WriteLine("> {0}.{1}", input.MethodBase.DeclaringType, input.MethodBase.Name);
stopwatch.Start();
// Invoke the next behavior in the chain.
var result = getNext()(input, getNext);
stopwatch.Stop();
// After invoking the method on the original target.
if (result.Exception != null)
{
Debug.WriteLine(
Call to decorated instance
"< {0}.{1} failed - after {3} ms",
input.MethodBase.DeclaringType, input.MethodBase.Name, result.Exception.GetType(),
stopwatch.ElapsedMilliseconds);
}
else
{
Debug.WriteLine("< {0}.{1} - after {2} ms",
input.MethodBase.DeclaringType, input.MethodBase.Name,
stopwatch.ElapsedMilliseconds);
}
Before each method call of decorated class
After each method call
public class DependencyConfig
{
public static void Configure(IUnityContainer container)
{
container.AddNewExtension<Interception>();
var connectionString = ConfigurationManager.ConnectionStrings["BankingDbContext"]
.ConnectionString;
container.RegisterType<IAccountRepository, AccountRepository>(
new InjectionConstructor(connectionString),
new Interceptor<InterfaceInterceptor>(),
new InterceptionBehavior<TimingBehavior>());
container.RegisterType<IUserAccountService, UserAccountService>(
new Interceptor<InterfaceInterceptor>(),
new InterceptionBehavior<TimingBehavior>());
}
}
42. Things to remember
• DI Patterns …
– Don’t be a Control Freak
– Constructor Injection is your friend
– Compose you object graphs in one place
– DI Containers are powerful but not magical
• … can help you achieve loosely coupled code
– Maintainable
– Testable
43. Going further …
• Mark Seemann’s book
and blog posts
– http://blog.ploeh.dk/
• Conversation about DI
in aspnet vNext
– http://forums.asp.net/t/1989008.aspx?Feedback+
on+ASP+NET+vNext+Dependency+Injection
• SOLID principles
47. Late-binding
• Dynamically decide which implementation to
protectuedsoeverride IController GetControllerInstance(RequestContext requestContext,
Type controllerType)
{
// how to compose an AccountController ?
if (controllerType == typeof(AccountController))
{
var repo = LoadInstanceFromPluginFolder<IAccountRepository>();
Plugin scenarios – scan assemblies in a folder for implementations
var service = new UserAccountService(repo);
return new AccountController(service);
}
// standard way in MVC to use default strategy
return base.GetControllerInstance(requestContext, controllerType);
50. SOLID
Single Responsibility Principle
Open Closed Principle
Liskov Substitution Principle
Interface Segregation Principle
Dependency Inversion Principe
Editor's Notes
Present you self
Talk about Dependency Injection
Dependency Injection patterns
You may know about it under a form or another, or ay have used tools
Who has ?
You must unlearn ! Need to understand the philosophy and concepts in order to use the tools properly
It’s easy to misuse the tools and miss some benefits
There is no magic !
Let’s see …
Inside a controller
Creating a dbcontext (Entity Framework) … imagine if that was ADO .NET
Selecting a few things
Passing it to the view…
Has anybody ever written code like that ?
That’s only a read page … imagine action with side effects…
Simplified, no error handling whatsoever
You may argue that it is loosely coupled … there’s only one class … but what a class !
Turned spaghetti into lasagna
Business depends on Data layer … it should be an implementation detail
Presentation depends on Business which depends on Data … which depends on EF … we’ll see that a bit later
But mostly about using components in isolation … this is not testable right now
Comment :
First encounter with need for loosely coupled code came from unit tests
Who write unit tests here ? Anybody who writes unit tests first ?
First encounter where you code MUST BE loosely coupled : unit tests ! Actually consume components out of the scope of the application
Tightly coupled code is hard to test or not testable at all … if it’s testable it’s not too tightly coupled
Interface of abstract class ….
I can’t do new I…..
The closest we can get is this ….
Note that even though we introduced interfaces, we still have a hard reference between all projects
Used in default Visual Studio Template for MVC apps until not so long ago
Comment about moving the interface into business
Where to put the interface ? Separate project “Abstractions” ? The consumer owns the interface
If you remember one thing, it’s that !
Top down
Can be done with Adapter pattern
Traditionnal approach would be :
Modify code
Subclass..