SlideShare une entreprise Scribd logo
1  sur  20
Télécharger pour lire hors ligne
ASP.NET MVC DI
Jason
Dependency injection (DI)
● 提高可維護性
● 建立寬鬆耦合性
● 增加可測試性
● 平行開發 (program to interface)
Example
public class DocumentPrinter
{
public void PrintDocument(string documentName)
{
var repository = new DocumentRepository();
var formatter = new DocumentFormatter();
var printer = new Printer();
var document = repository.GetDocumentByName(documentName);
var formattedDocument = formatter.Format(document);
printer.Print(formattedDocument);
}
}
var document = new DocumentPrint();
documentPrinter.PrintDocument(@”C:xxx.doc”);
Contructor DI
public class DocumentPrinter
{
private DocumentRepository _repository;
private DocumentFormatter _formatter;
private Printer _printer;
public DocumentPrinter(DocumentRepository repository, DocumentFormatter formatter, Printer printer)
{
_repository = repository; _formatter = formatter; _printer = printer;
}
public void PrintDocument(string documentName)
{
var document = _repository.GetDocumentByName(documentName);
var formattedDocument = _formatter.Format(document);
_printer.Print(formattedDocument);
}
}
Contructor DI
var repository = new DocumentRepository();
var formatter = new DocumentFormatter();
var printer = new Printer();
var documentPrinter = new DocumentPrinter(repository, formatter, printer);
documentPrinter.PrintDocument(@”C:xxx.doc”);
DI - Interface
DI - Interface
public class DocumentPrinter
{
private IDocumentRepository _repository;
private IDocumentFormatter _formatter;
private IPrinter _printer;
public DocumentPrinter(IDocumentRepository repository, IDocumentFormatter formatter, IPrinter printer)
{
_repository = repository; _formatter = formatter; _printer = printer;
}
public void PrintDocument(string documentName)
{
var document = _repository.GetDocumentByName(documentName);
var formattedDocument = _formatter.Format(document);
_printer.Print(formattedDocument);
}
}
DI - Interface
var repository = new FilesystemDocumentRepository();
var formatter = new DocumentFormatter();
var printer = new Printer();
var documentPrinter = new DocumentPrinter(repository, formatter, printer);
documentPrinter.PrintDocument(@”C:xxx.doc”);
OR
var repository = new DatabaseDocumentRepository();
var formatter = new DocumentFormatter();
var printer = new Printer();
var documentPrinter = new DocumentPrinter(repository, formatter, printer);
documentPrinter.PrintDocument(”xxx.doc”);
DI Container
Ex. StructureMap、Castle、Windsor、Ninject、Autofac and Unity
using StructureMap:
var container = new Container(x =>
{
x.For<IDocumentRepository>().Use<DocumentRepository>();
x.For<IDocumentFormatter>().Use<DocumentFormatter>();
x.For<IPrinter>().Use<Printer>();
});
var documentPrinter = container.GetInstance<DocumentPrinter>();
documentPrinter.PrintDocument(@”C:xxx.doc”);
DI - ASP.NET MVC
Controller 不應該執行:
直接進行資料庫存取
直接和檔案系統溝通
直接傳送 e-mail
直接呼叫 web service
DI - ASP.NET MVC
● Controller factory
● Dependency resolver
DI - Controller Factory
public interface IMessageProvider
{
string GetMessage();
}
public class EnglishMessageProvider : IMessageProvider
{
public string GetMessage()
{
return "Hello!";
}
}
DI - Controller Factory
HomeController.cs
public class HomeController : Controller
{
private IMessageProvider _messageProvider;
public HomeController( IMessageProvider messageProvider )
{
_messageProvider = messageProvider;
}
public ActionResult Index()
{
ViewBag.Message = _messageProvider.GetMessage();
return View();
}
}
DI - Controller Factory
StructureMapControllerFactory.cs
public class StructureMapControllerFactory: DefaultControllerFactory
{
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
if (controllerType == null)
{
throw new HttpException(404, "Controller not found");
}
var container = new Container(x =>
{
x.For<IMessageProvider>().Use<EnglishMessageProvider>();
});
return container.GetInstance(controllerType) as IController;
}
}
DI - Controller Factory
Global.asax.cs
protected void Application_Start()
{
ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory());
}
DI - Dependency Resolver
● IDependencyResolver
● DependencyResolver
DI - Dependency Resolver
Create ControllerDependency
Resolver
Create Controller
DefaultController
Activator
Activator
CreateInstance
DI Container
Create Instance
NO
Yes
DI - Dependency Resolver
public class StructureMapDependencyResolver : IDependencyResolver
{
public object GetService(Type serviceType)
{
var container = new Container(x =>
{
x.For<IMessageProvider>().Use<EnglishMessageProvider>();
});
var instance = container.TryGetInstance(serviceType);
if (instance == null && !serviceType.IsAbstract && !serviceType.IsInterface)
{
instance = container.GetInstance(serviceType);
}
return instance;
}
}
DI - Dependency Resolver
Global.asax.cs
protected void Application_Start()
{
DependencyResolver.SetResolver(new StructureMapDependencyResolver());
}
Reference
ASP.NET MVC4
http://www.books.com.tw/products/0010589490
StructureMap
http://structuremap.github.io/quickstart/

Contenu connexe

Tendances

Azure Mobile Services .NET Backend
Azure Mobile Services .NET BackendAzure Mobile Services .NET Backend
Azure Mobile Services .NET BackendShiju Varghese
 
#win8acad : Building Metro Style Apps with XAML for .NET Developers
#win8acad : Building Metro Style Apps with XAML for .NET Developers#win8acad : Building Metro Style Apps with XAML for .NET Developers
#win8acad : Building Metro Style Apps with XAML for .NET DevelopersFrederik De Bruyne
 
MongoDB.local Paris Keynote
MongoDB.local Paris KeynoteMongoDB.local Paris Keynote
MongoDB.local Paris KeynoteMongoDB
 
Data Management 2: Conquering Data Proliferation
Data Management 2: Conquering Data ProliferationData Management 2: Conquering Data Proliferation
Data Management 2: Conquering Data ProliferationMongoDB
 
Using Azure Storage for Mobile
Using Azure Storage for MobileUsing Azure Storage for Mobile
Using Azure Storage for MobileGlenn Stephens
 
Serverless Apps - droidcon london 2012
Serverless Apps - droidcon london 2012Serverless Apps - droidcon london 2012
Serverless Apps - droidcon london 2012Friedger Müffke
 
Format xls sheets Demo Mode
Format xls sheets Demo ModeFormat xls sheets Demo Mode
Format xls sheets Demo ModeJared Bourne
 
Video WebChat Conference Tool
Video WebChat Conference ToolVideo WebChat Conference Tool
Video WebChat Conference ToolSergiu Gordienco
 
New text document
New text documentNew text document
New text documentTam Ngo
 
TechDays 2016 - Case Study: Azure + IOT + LoRa = ”Leven is Water”
TechDays 2016 - Case Study: Azure + IOT + LoRa = ”Leven is Water”TechDays 2016 - Case Study: Azure + IOT + LoRa = ”Leven is Water”
TechDays 2016 - Case Study: Azure + IOT + LoRa = ”Leven is Water”Rick van den Bosch
 

Tendances (13)

Azure Mobile Services .NET Backend
Azure Mobile Services .NET BackendAzure Mobile Services .NET Backend
Azure Mobile Services .NET Backend
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
Azure DocumentDB
Azure DocumentDBAzure DocumentDB
Azure DocumentDB
 
#win8acad : Building Metro Style Apps with XAML for .NET Developers
#win8acad : Building Metro Style Apps with XAML for .NET Developers#win8acad : Building Metro Style Apps with XAML for .NET Developers
#win8acad : Building Metro Style Apps with XAML for .NET Developers
 
MongoDB.local Paris Keynote
MongoDB.local Paris KeynoteMongoDB.local Paris Keynote
MongoDB.local Paris Keynote
 
Fetch data from form
Fetch data from formFetch data from form
Fetch data from form
 
Data Management 2: Conquering Data Proliferation
Data Management 2: Conquering Data ProliferationData Management 2: Conquering Data Proliferation
Data Management 2: Conquering Data Proliferation
 
Using Azure Storage for Mobile
Using Azure Storage for MobileUsing Azure Storage for Mobile
Using Azure Storage for Mobile
 
Serverless Apps - droidcon london 2012
Serverless Apps - droidcon london 2012Serverless Apps - droidcon london 2012
Serverless Apps - droidcon london 2012
 
Format xls sheets Demo Mode
Format xls sheets Demo ModeFormat xls sheets Demo Mode
Format xls sheets Demo Mode
 
Video WebChat Conference Tool
Video WebChat Conference ToolVideo WebChat Conference Tool
Video WebChat Conference Tool
 
New text document
New text documentNew text document
New text document
 
TechDays 2016 - Case Study: Azure + IOT + LoRa = ”Leven is Water”
TechDays 2016 - Case Study: Azure + IOT + LoRa = ”Leven is Water”TechDays 2016 - Case Study: Azure + IOT + LoRa = ”Leven is Water”
TechDays 2016 - Case Study: Azure + IOT + LoRa = ”Leven is Water”
 

En vedette

ASP.NET MVC difference between questions list 1
ASP.NET MVC difference between questions list 1ASP.NET MVC difference between questions list 1
ASP.NET MVC difference between questions list 1Umar Ali
 
Resolve dependency of dependencies using Inversion of Control and dependency ...
Resolve dependency of dependencies using Inversion of Control and dependency ...Resolve dependency of dependencies using Inversion of Control and dependency ...
Resolve dependency of dependencies using Inversion of Control and dependency ...Akhil Mittal
 
Technical Video Training Sites- 1
Technical Video Training Sites- 1Technical Video Training Sites- 1
Technical Video Training Sites- 1Umar Ali
 
Inversion of control using dependency injection in Web APIs using Unity Conta...
Inversion of control using dependency injection in Web APIs using Unity Conta...Inversion of control using dependency injection in Web APIs using Unity Conta...
Inversion of control using dependency injection in Web APIs using Unity Conta...Akhil Mittal
 
Difference between authentication and authorization in asp.net
Difference between authentication and authorization in asp.netDifference between authentication and authorization in asp.net
Difference between authentication and authorization in asp.netUmar Ali
 
State Management In ASP.NET And ASP.NET MVC
State Management In ASP.NET And ASP.NET MVCState Management In ASP.NET And ASP.NET MVC
State Management In ASP.NET And ASP.NET MVCjinaldesailive
 
MS.Net Interview Questions - Simplified
MS.Net Interview Questions - SimplifiedMS.Net Interview Questions - Simplified
MS.Net Interview Questions - SimplifiedMohd Manzoor Ahmed
 
ASP.NET MVC Interview Questions and Answers by Shailendra Chauhan
ASP.NET MVC Interview Questions and Answers by Shailendra ChauhanASP.NET MVC Interview Questions and Answers by Shailendra Chauhan
ASP.NET MVC Interview Questions and Answers by Shailendra ChauhanShailendra Chauhan
 
Top 100 .Net Interview Questions and Answer
Top 100 .Net Interview Questions and AnswerTop 100 .Net Interview Questions and Answer
Top 100 .Net Interview Questions and AnswerVineet Kumar Saini
 
C# ASP.NET WEB API APPLICATION DEVELOPMENT
C# ASP.NET WEB API APPLICATION DEVELOPMENTC# ASP.NET WEB API APPLICATION DEVELOPMENT
C# ASP.NET WEB API APPLICATION DEVELOPMENTDr. Awase Khirni Syed
 

En vedette (12)

ASP.NET MVC difference between questions list 1
ASP.NET MVC difference between questions list 1ASP.NET MVC difference between questions list 1
ASP.NET MVC difference between questions list 1
 
Resolve dependency of dependencies using Inversion of Control and dependency ...
Resolve dependency of dependencies using Inversion of Control and dependency ...Resolve dependency of dependencies using Inversion of Control and dependency ...
Resolve dependency of dependencies using Inversion of Control and dependency ...
 
PDFArticle
PDFArticlePDFArticle
PDFArticle
 
Technical Video Training Sites- 1
Technical Video Training Sites- 1Technical Video Training Sites- 1
Technical Video Training Sites- 1
 
Inversion of control using dependency injection in Web APIs using Unity Conta...
Inversion of control using dependency injection in Web APIs using Unity Conta...Inversion of control using dependency injection in Web APIs using Unity Conta...
Inversion of control using dependency injection in Web APIs using Unity Conta...
 
Angularjs Basics
Angularjs BasicsAngularjs Basics
Angularjs Basics
 
Difference between authentication and authorization in asp.net
Difference between authentication and authorization in asp.netDifference between authentication and authorization in asp.net
Difference between authentication and authorization in asp.net
 
State Management In ASP.NET And ASP.NET MVC
State Management In ASP.NET And ASP.NET MVCState Management In ASP.NET And ASP.NET MVC
State Management In ASP.NET And ASP.NET MVC
 
MS.Net Interview Questions - Simplified
MS.Net Interview Questions - SimplifiedMS.Net Interview Questions - Simplified
MS.Net Interview Questions - Simplified
 
ASP.NET MVC Interview Questions and Answers by Shailendra Chauhan
ASP.NET MVC Interview Questions and Answers by Shailendra ChauhanASP.NET MVC Interview Questions and Answers by Shailendra Chauhan
ASP.NET MVC Interview Questions and Answers by Shailendra Chauhan
 
Top 100 .Net Interview Questions and Answer
Top 100 .Net Interview Questions and AnswerTop 100 .Net Interview Questions and Answer
Top 100 .Net Interview Questions and Answer
 
C# ASP.NET WEB API APPLICATION DEVELOPMENT
C# ASP.NET WEB API APPLICATION DEVELOPMENTC# ASP.NET WEB API APPLICATION DEVELOPMENT
C# ASP.NET WEB API APPLICATION DEVELOPMENT
 

Similaire à Asp.net MVC DI

Devoxx08 - Nuxeo Core, JCR 2, CMIS
Devoxx08 - Nuxeo Core, JCR 2, CMIS Devoxx08 - Nuxeo Core, JCR 2, CMIS
Devoxx08 - Nuxeo Core, JCR 2, CMIS Nuxeo
 
HDTR images with Photoshop Javascript Scripting
HDTR images with Photoshop Javascript ScriptingHDTR images with Photoshop Javascript Scripting
HDTR images with Photoshop Javascript ScriptingDavid Gómez García
 
Android Kit Kat - Printing Framework
Android Kit Kat - Printing FrameworkAndroid Kit Kat - Printing Framework
Android Kit Kat - Printing FrameworkPaul Lammertsma
 
Hack an ASP .NET website? Hard, but possible!
Hack an ASP .NET website? Hard, but possible! Hack an ASP .NET website? Hard, but possible!
Hack an ASP .NET website? Hard, but possible! Vladimir Kochetkov
 
Oleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoCOleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoCOleksandr Valetskyy
 
Developing your first application using FIWARE
Developing your first application using FIWAREDeveloping your first application using FIWARE
Developing your first application using FIWAREFIWARE
 
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17LogeekNightUkraine
 
Logisland "Event Mining at scale"
Logisland "Event Mining at scale"Logisland "Event Mining at scale"
Logisland "Event Mining at scale"Thomas Bailet
 
Spring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in HeavenSpring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in HeavenJoshua Long
 
Altium script examples reference
Altium  script examples reference Altium  script examples reference
Altium script examples reference jigg1777
 
服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScriptQiangning Hong
 
Nuxeo - OpenSocial
Nuxeo - OpenSocialNuxeo - OpenSocial
Nuxeo - OpenSocialThomas Roger
 
Java Configuration Deep Dive with Spring
Java Configuration Deep Dive with SpringJava Configuration Deep Dive with Spring
Java Configuration Deep Dive with SpringJoshua Long
 
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rulesSrijan Technologies
 

Similaire à Asp.net MVC DI (20)

Devoxx08 - Nuxeo Core, JCR 2, CMIS
Devoxx08 - Nuxeo Core, JCR 2, CMIS Devoxx08 - Nuxeo Core, JCR 2, CMIS
Devoxx08 - Nuxeo Core, JCR 2, CMIS
 
HDTR images with Photoshop Javascript Scripting
HDTR images with Photoshop Javascript ScriptingHDTR images with Photoshop Javascript Scripting
HDTR images with Photoshop Javascript Scripting
 
Android Kit Kat - Printing Framework
Android Kit Kat - Printing FrameworkAndroid Kit Kat - Printing Framework
Android Kit Kat - Printing Framework
 
Hack an ASP .NET website? Hard, but possible!
Hack an ASP .NET website? Hard, but possible! Hack an ASP .NET website? Hard, but possible!
Hack an ASP .NET website? Hard, but possible!
 
Oleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoCOleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoC
 
Synapse india basic php development part 1
Synapse india basic php development part 1Synapse india basic php development part 1
Synapse india basic php development part 1
 
Vertx SouJava
Vertx SouJavaVertx SouJava
Vertx SouJava
 
Vertx daitan
Vertx daitanVertx daitan
Vertx daitan
 
Tdd,Ioc
Tdd,IocTdd,Ioc
Tdd,Ioc
 
Developing your first application using FIWARE
Developing your first application using FIWAREDeveloping your first application using FIWARE
Developing your first application using FIWARE
 
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
 
Logisland "Event Mining at scale"
Logisland "Event Mining at scale"Logisland "Event Mining at scale"
Logisland "Event Mining at scale"
 
Spring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in HeavenSpring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in Heaven
 
Altium script examples reference
Altium  script examples reference Altium  script examples reference
Altium script examples reference
 
服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript
 
Nuxeo - OpenSocial
Nuxeo - OpenSocialNuxeo - OpenSocial
Nuxeo - OpenSocial
 
srgoc
srgocsrgoc
srgoc
 
Java Configuration Deep Dive with Spring
Java Configuration Deep Dive with SpringJava Configuration Deep Dive with Spring
Java Configuration Deep Dive with Spring
 
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
 
Having Fun with Play
Having Fun with PlayHaving Fun with Play
Having Fun with Play
 

Plus de LearningTech

Plus de LearningTech (20)

vim
vimvim
vim
 
PostCss
PostCssPostCss
PostCss
 
ReactJs
ReactJsReactJs
ReactJs
 
Docker
DockerDocker
Docker
 
Semantic ui
Semantic uiSemantic ui
Semantic ui
 
node.js errors
node.js errorsnode.js errors
node.js errors
 
Process control nodejs
Process control nodejsProcess control nodejs
Process control nodejs
 
Expression tree
Expression treeExpression tree
Expression tree
 
SQL 效能調校
SQL 效能調校SQL 效能調校
SQL 效能調校
 
flexbox report
flexbox reportflexbox report
flexbox report
 
Vic weekly learning_20160504
Vic weekly learning_20160504Vic weekly learning_20160504
Vic weekly learning_20160504
 
Reflection &amp; activator
Reflection &amp; activatorReflection &amp; activator
Reflection &amp; activator
 
Peggy markdown
Peggy markdownPeggy markdown
Peggy markdown
 
Node child process
Node child processNode child process
Node child process
 
20160415ken.lee
20160415ken.lee20160415ken.lee
20160415ken.lee
 
Peggy elasticsearch應用
Peggy elasticsearch應用Peggy elasticsearch應用
Peggy elasticsearch應用
 
Expression tree
Expression treeExpression tree
Expression tree
 
Vic weekly learning_20160325
Vic weekly learning_20160325Vic weekly learning_20160325
Vic weekly learning_20160325
 
D3js learning tips
D3js learning tipsD3js learning tips
D3js learning tips
 
git command
git commandgit command
git command
 

Dernier

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024SynarionITSolutions
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 

Dernier (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

Asp.net MVC DI

  • 2. Dependency injection (DI) ● 提高可維護性 ● 建立寬鬆耦合性 ● 增加可測試性 ● 平行開發 (program to interface)
  • 3. Example public class DocumentPrinter { public void PrintDocument(string documentName) { var repository = new DocumentRepository(); var formatter = new DocumentFormatter(); var printer = new Printer(); var document = repository.GetDocumentByName(documentName); var formattedDocument = formatter.Format(document); printer.Print(formattedDocument); } } var document = new DocumentPrint(); documentPrinter.PrintDocument(@”C:xxx.doc”);
  • 4. Contructor DI public class DocumentPrinter { private DocumentRepository _repository; private DocumentFormatter _formatter; private Printer _printer; public DocumentPrinter(DocumentRepository repository, DocumentFormatter formatter, Printer printer) { _repository = repository; _formatter = formatter; _printer = printer; } public void PrintDocument(string documentName) { var document = _repository.GetDocumentByName(documentName); var formattedDocument = _formatter.Format(document); _printer.Print(formattedDocument); } }
  • 5. Contructor DI var repository = new DocumentRepository(); var formatter = new DocumentFormatter(); var printer = new Printer(); var documentPrinter = new DocumentPrinter(repository, formatter, printer); documentPrinter.PrintDocument(@”C:xxx.doc”);
  • 7. DI - Interface public class DocumentPrinter { private IDocumentRepository _repository; private IDocumentFormatter _formatter; private IPrinter _printer; public DocumentPrinter(IDocumentRepository repository, IDocumentFormatter formatter, IPrinter printer) { _repository = repository; _formatter = formatter; _printer = printer; } public void PrintDocument(string documentName) { var document = _repository.GetDocumentByName(documentName); var formattedDocument = _formatter.Format(document); _printer.Print(formattedDocument); } }
  • 8. DI - Interface var repository = new FilesystemDocumentRepository(); var formatter = new DocumentFormatter(); var printer = new Printer(); var documentPrinter = new DocumentPrinter(repository, formatter, printer); documentPrinter.PrintDocument(@”C:xxx.doc”); OR var repository = new DatabaseDocumentRepository(); var formatter = new DocumentFormatter(); var printer = new Printer(); var documentPrinter = new DocumentPrinter(repository, formatter, printer); documentPrinter.PrintDocument(”xxx.doc”);
  • 9. DI Container Ex. StructureMap、Castle、Windsor、Ninject、Autofac and Unity using StructureMap: var container = new Container(x => { x.For<IDocumentRepository>().Use<DocumentRepository>(); x.For<IDocumentFormatter>().Use<DocumentFormatter>(); x.For<IPrinter>().Use<Printer>(); }); var documentPrinter = container.GetInstance<DocumentPrinter>(); documentPrinter.PrintDocument(@”C:xxx.doc”);
  • 10. DI - ASP.NET MVC Controller 不應該執行: 直接進行資料庫存取 直接和檔案系統溝通 直接傳送 e-mail 直接呼叫 web service
  • 11. DI - ASP.NET MVC ● Controller factory ● Dependency resolver
  • 12. DI - Controller Factory public interface IMessageProvider { string GetMessage(); } public class EnglishMessageProvider : IMessageProvider { public string GetMessage() { return "Hello!"; } }
  • 13. DI - Controller Factory HomeController.cs public class HomeController : Controller { private IMessageProvider _messageProvider; public HomeController( IMessageProvider messageProvider ) { _messageProvider = messageProvider; } public ActionResult Index() { ViewBag.Message = _messageProvider.GetMessage(); return View(); } }
  • 14. DI - Controller Factory StructureMapControllerFactory.cs public class StructureMapControllerFactory: DefaultControllerFactory { protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { if (controllerType == null) { throw new HttpException(404, "Controller not found"); } var container = new Container(x => { x.For<IMessageProvider>().Use<EnglishMessageProvider>(); }); return container.GetInstance(controllerType) as IController; } }
  • 15. DI - Controller Factory Global.asax.cs protected void Application_Start() { ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory()); }
  • 16. DI - Dependency Resolver ● IDependencyResolver ● DependencyResolver
  • 17. DI - Dependency Resolver Create ControllerDependency Resolver Create Controller DefaultController Activator Activator CreateInstance DI Container Create Instance NO Yes
  • 18. DI - Dependency Resolver public class StructureMapDependencyResolver : IDependencyResolver { public object GetService(Type serviceType) { var container = new Container(x => { x.For<IMessageProvider>().Use<EnglishMessageProvider>(); }); var instance = container.TryGetInstance(serviceType); if (instance == null && !serviceType.IsAbstract && !serviceType.IsInterface) { instance = container.GetInstance(serviceType); } return instance; } }
  • 19. DI - Dependency Resolver Global.asax.cs protected void Application_Start() { DependencyResolver.SetResolver(new StructureMapDependencyResolver()); }