Mastering Ninject for Dependency Injection - Daniel Baharestani - E-Book

Mastering Ninject for Dependency Injection E-Book

Daniel Baharestani

0,0
26,39 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Dependency injection is an approach to creating loosely coupled applications. Maintainability, testability, and extensibility are just a few advantages of loose coupling. Ninject is a software library which automates almost everything that we need in order to implement a dependency injection pattern.

Mastering Ninject for Dependency Injection will teach you everything you need to know in order to implement dependency injection using Ninject in a real-life project. Not only does it teach you about Ninject core framework features that are essential for implementing dependency injection, but it also explores the power of Ninject's most useful extensions and demonstrates how to apply them.

Mastering Ninject for Dependency Injection starts by introducing you to dependency injection and what it's meant for with the help of sufficient examples.

Eventually, you'll learn how to integrate Ninject into your practical project and how to use its basic features. Also, you will go through scenarios wherein advanced features of Ninject, such as Multi-binding, Contextual binding, providers, factories and so on, come into play. As you progress, Mastering Ninject for Dependency Injection will show you how to create a multilayer application that demonstrates the use of Ninject on different application types such as MVC, WPF, WCF, and so on. Finally, you will learn the benefits of using the powerful extensions of Ninject.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 151

Veröffentlichungsjahr: 2013

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Mastering Ninject for Dependency Injection
Credits
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers and more
Why Subscribe?
Free Access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Understanding Dependency Injection
What is Dependency Injection?
DI or Inversion of Control (IoC)
How can DI help?
My First DI Application
DI Containers
Why use Ninject?
Summary
2. Getting Started with Ninject
Hello Ninject!
It's all about Binding
Object Lifetime
Transient scope
Singleton scope
Thread scope
Request scope
Custom scope
Ninject modules
XML configuration
How to use XML configuration
Convention over configuration
Selecting the assemblies
Selecting the components
Filtering the selected components
Explicit inclusion and exclusion
Selecting service types
Configuring the Bindings
Summary
3. Meeting Real-world Requirements
DI patterns and antipatterns
Constructor Injection
Initializer methods and properties
Service Locator
Multi binding and contextual binding
Implementing the plugin model
Contextual binding
Named binding
Resolving metadata
Attribute-based binding
Target-based conditions
Generic helper
Custom providers
Activation context
Factory Methods
Dynamic factories
The Shape Factory example
Using convention
Selecting service types
Defining Binding Generator
Telecom Switch example
Custom Instance Providers
Func
Lazy
Summary
4. Ninject in Action
Windows Forms applications
WPF and Silverlight applications
ASP.NET MVC applications
Validator injection
Filter injection
Conditional filtering (When)
Contextual arguments (With)
WCF applications
ASP.NET Web Forms applications
Summary
5. Doing More with Extensions
Interception
Setup Interception
Member Interception
Type Interception
Multiple Interceptors
Intercept Attribute
Mocking Kernel
Extending Ninject
Summary
Index

Mastering Ninject for Dependency Injection

Mastering Ninject for Dependency Injection

Copyright © 2013 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: September 2013

Production Reference: 1190913

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK..

ISBN 978-1-78216-620-7

www.packtpub.com

Cover Image by Daniel Baharestani (<[email protected]>) and Sheetal Aute (<[email protected]>)

Credits

Author

Daniel Baharestani

Reviewers

Remo Gloor

Daniel Allen

Matt Duffield

Ted Winslow

Acquisition Editor

Pramila Balan

Commissioning Editor

Nikhil Chinnari

Technical Editors

Iram Malik

Krishnaveni Haridas

Veena Pagare

Project Coordinator

Romal Karani

Proofreader

Clyde Jenkins

Indexer

Monica Ajmera

Graphics

Ronak Dhruv

Production Coordinator

Conidon Miranda

Cover Work

Conidon Miranda

About the Author

Daniel Baharestani is an experienced IT professional living in Australia. He has a BSc in software engineering and has over 10 years of professional experience in design and development of enterprise applications, mostly focused on Microsoft technologies. Daniel is currently working at 3P Learning, which is a global leader in online learning for school-aged students with its flagship platform, Mathletics—used by more than 3.5 million students in over 10,000 schools worldwide.

A book is like a song, which may usually be referred to by its singer's name, whereas many people are involved in the background to make it happen.

First, I am deeply indebted to my wife, Mona, who has taken all my responsibilities during this period. I understand how hard it was for her to do everything alone that we used to do together.

My special thanks goes to Remo Gloor, the main developers of Ninject, who kindly accepted the final technical review of this book, and other technical reviewers, including Daniel Allen, Matt Duffield, and Ted Winslow for providing valuable feedback.

I would also like to thank my manager, Houman, for being helpful and encouraging, and for understanding how important this book was to me. It would be much difficult to have it done without his support.

Finally, I should acknowledge the whole Packt team, who gave me this opportunity and guided me through this process, including but definitely not limited to, Nikhil Chinnari and Yogesh Dalvi, my commissioning editors, Sneha Modi and Romal Karani, my project coordinators, and Shrutika Kalbag, the author relationship executive for opening a door.

About the Reviewers

Remo Gloor has worked as a Software Architect at bbv Software Services AG in Switzerland for many years. During this time, he was using Ninject in several projects. At the beginning, he was a user of Ninject. Later, he contributed with several extensions. In 2010, he became manager and the main contributor to Ninject, which was developed originally by Nate Kohari and Ian Davis.

Besides his interest in dependency injection and IoC containers, he has also a strong interest in service-oriented and message-driven architectures, as well as event sourcing. Because of this, he contributed to the ActiveMq support to NServiceBus.

He blogs on http://www.planetgeek.ch/author/remo-gloor/ mainly about Ninject. He also answers many Ninject-related questions on stackoverflow: http://stackoverflow.com/users/448580/remo-gloor.

Daniel Allen is a Chicago-based developer who specializes in ASP.NET MVC 4 development and enterprise architecture design. He develops primarily in C#, JavaScript, and Objective-C. Because of his heavy focus on enterprise architecture design, Dan has experience in an array of patterns and tools that he has effectively and logically combined together to meet a project's unique needs. Dan holds a B.S. in Management Information Systems and an MBA with a concentration in Information Systems.

Dan spends much of his free time working on development-related side contracts and searching for the next great startup idea. He aspires to start a consulting firm that will provide capital for the various startup ideas one day. For recreation, he enjoys training and competing in various marathons, and aspires to complete a full iron man competition one day.

He has formerly worked with Millennium Information Services, Inc. as an ASP.NET MVC Web Developer. His primary tasks in this role were MVC 4 Razor development, HTML 5 frontend GUI design, enterprise architecture design, and WCF, Oracle database, and agile development. He has also worked for Arc Worldwide / Leo Burnett as an Associate Software Engineer. His primary tasks in this role were ASP.NET Web Forms development, frontend GUI design, and he also worked on SQL Server database. Dan has also worked with American Concrete Pavement Association as a Software Engineer. His primary tasks in this role were ASP.NET Web Forms and MVC 4 development, iOS mobile development, and SQL Server database, graphics and media development.

For Dan's complete professional history and his online interactive portfolio, please visit http://www.apexwebz.com.

I would like to thank my family for their ongoing support. My father inspired me to start working in this field, and now I can't picture myself doing anything else. I would also like to thank my close friend, past boss, and ongoing mentor, Robert Rodden, for helping me at every step of the way in my professional career.

Matt Duffield is a software architect, and has over 17 years of experience working in IT. He enjoys building a rich line of business applications that focus on great user experiences while providing excellent business intelligence, such as dashboards and expert systems. His current focus is on client-side MVC architecture and building cross-platform solutions. Matt is very active in the community, speaking at user groups and code camps. He is an INETA speaker and a Microsoft MVP in client development. He is the co-author of Microsoft Silverlight 5: Building Rich Enterprise Dashboards, Packt Publishing. His blog can be found at http://mattduffield.wordpress.com. You can follow him on Twitter at @mattduffield. Matt is also the leader of the Charlotte ALT.NET user group (http://www.meetup.com/charlottealtnet/) and Charlotte Game Dev user group (http://www.meetup.com/Charlotte-Game-Dev/). He is also the Vice President of the Charlotte Enterprise Developers Guild (http://www.developersguild.org/) and also board member of the Carolina Code Camp.

Ted Winslow has been one of those programmers who impressed the likes of NASA and Boeing with his skills behind a keyboard ever since his sixth grade. Even when he isn't working for one of the big names, he's freelancing for multimillion-dollar shops, and considers writing code a way to relax in his downtime. He started writing code while young and did it with little more than a basic starter book and a half-broken computer. Against all odds, he has now a lengthy and respected work history with code chops for which large and small companies hunger. Nowadays, he's spotted helping people in his free time to make sure the young programmers understand and have a chance to live their dream, even when the odds are stacked against them.

I'd like to thank my friends for both the encouragement they've provided during my career and for putting up with me every day. You all mean a lot to me.

www.PacktPub.com

Support files, eBooks, discount offers and more

You might want to visit www.PacktPub.com for support files and downloads related to your book.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

http://PacktLib.PacktPub.com

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books. 

Why Subscribe?

Fully searchable across every book published by PacktCopy and paste, print and bookmark contentOn demand and accessible via web browser

Free Access for Packt account holders

If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.

Preface

Mastering Ninject for Dependency Injection demonstrates how Ninject facilitates the implementation of Dependency Injection to solve common design problems of real-life applications in a simple and easy-to-understand format. This book will teach you everything you need in order to implement Dependency Injection using Ninject in a real-life project. Not only does it teach the Ninject core framework features which are essential for implementing DI, but it also explores the power of Ninject's most useful extensions, and demonstrates how to apply them in a real-life application.

What this book covers

Chapter 1, Understanding Dependency Injection, introduces Dependency Injection concepts and describes the advantages of using this technique. We will also go through a simple example and implement the principles and patterns related to DI techniques. After understanding what a DI container is, we will discuss why Ninject is a suitable choice.

Chapter 2, Getting Started with Ninject, teaches the user how to add Ninject to a practical project and how to use the basic features of this framework. The chapter starts with an example demonstrating how to set up and use Ninject in a Hello World project. Then, we will talk about how Ninject resolves dependencies and how it manages object lifetime. We will also cover the code-based configuration using Ninject modules and XML-based configuration. The final section of this chapter describes how to configure a large application which includes hundreds of services using Ninject conventions. By the end of this chapter, the user will be able to set up and use the basic features of Ninject.

Chapter 3, Meeting Real-world Requirements, introduces more advanced features of Ninject which are necessary in order to implement DI in real-world situations. The chapter starts with an introduction to some patterns and antipatterns related to Ninject. We will then go through real examples and see how Ninject can solve such kind of problems. By the end of this chapter, the user is expected to know almost all of the significant features of Ninject.

Chapter 4, Ninject in Action, shows how to set up different types of applications using Ninject. We will implement a concrete scenario using a variety of application types, including but not limited to, WPF, ASP .NET MVC, and WCF, to see how to set up and use Ninject for injecting the dependencies. By the end of this chapter, the user should be able to set up and use Ninject for all kinds of described applications.

Chapter 5, Doing More with Extensions, will show how Interception is a solution for cross-cutting concerns, and how to use Mocking Kernel as a test asset. While the core library of Ninject is kept clean and simple, Ninject is a highly extensible DI container, and it is possible to extend its power by using extension plugins. We will also see how Ninject can be extended.

What you need for this book

The examples of the book are written in Microsoft Visual Studio 2012; however, the target framework is set to .NET 4.0 so that they can be easily built using MSBuild and .NET Framework 4.0, even if you do not have Visual Studio 2012.

In the ASP.NET MVC application, we used MVC 3, and Microsoft SQL Server Compact 4.0 is used for SQL Data Layer.

You need an Internet connection to download required references and online packages, such as Ninject and its extensions. Having NuGet package manager on your system facilitates installing of referenced packages, but it is not required, as wherever we need to install such packages, the instruction for manually downloading and referencing the binaries is also provided.

We have also used NUnit for our Unit Tests, which is freely available for download via NuGet or NUnit website.

Who this book is for

This book is for all software developers and architects who are willing to create maintainable, loosely coupled, extensible, and testable applications. Because Ninject targets the .NET platform, this book is not suitable for software developers of other platforms. You should be comfortable with object oriented principals, and have a fair understanding of inheritance and abstraction. Being familiar with design patterns and general concept of unit testing is also a great help, but no knowledge of Dependency Injection is assumed. Although Ninject can be used in any .NET programming languages, the examples of this book are all in C#, so the reader is assumed to be familiar with this language.

Conventions

In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

Code words in text are shown as follows: "The following example shows how to use the ILogger interface."

A block of code is set as follows:

[Inject] public ILogger Logger {get; set;} public void DoSomething() { Logger.Debug("Doing something..."); }

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

kernel.Bind(x => x .FromThisAssembly() .SelectAllClasses() .InNamespaces("Northwind.Controllers") .BindBase());

Any command-line input or output is written as follows:

2013-05-23 05:04:40 INFO LogSamples.Consumer - Doing something...

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "The first one is called when the hyperlink Create New is clicked using HTTP GET method ".

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title through the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the erratasubmissionform link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website, or added to any list of existing errata, under the Errata section of that title.

Piracy

Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]>