SlideShare uma empresa Scribd logo
1 de 20
Baixar para ler offline
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/

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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”
 

Destaque

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
 

Destaque (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
 

Semelhante a 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
 

Semelhante a 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 daitan
Vertx daitanVertx daitan
Vertx daitan
 
Vertx SouJava
Vertx SouJavaVertx SouJava
Vertx SouJava
 
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
 

Mais de LearningTech

Mais 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
 

Último

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
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
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
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
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 

Último (20)

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
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
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
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...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 

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()); }