I have been working alot on MVC3 now a days and use Dependency Injection ninject etc.
I find it useful in Testing, don't make concrete implementation of classes like Model but instead injected.
My Questions:
How do we explain DI. Any simple definition to it.?
The benefits of DI?
Can we use DI in ASP.NET web forms?
Thanks
Dependency injection is eliminating the objects dependencies of concrete classes.
Benefits:
It allowed to use an abstract interface instead of a concrete class.
This makes lots of (large) applications to be more manageable, if you need to swap out a class, its easier to inherit from an interface and make the IoC container switch to another class.
And if you're looking to use DI in ASP.NET Web Forms in the business logic, yes you can.
Dependency injection means giving an object its instance variables.
Here is a great article about it:
http://jamesshore.com/Blog/Dependency-Injection-Demystified.html.
Can't be simplier, I think.
Benefits: Loose coupling. Easy implementation changes by just editing config file. Easy testing with mocks.
In WebForms? Sure, I've been working on a project where we successfully used Castle Windsor to inject our Repositories.
Brad Wilson has a really good ASP.NET MVC 3 Service Location blog series. It may help you see the value.
Related
I want to separate my ASP. NET MVC 5 + WebApi2 solution into separate logical projects, so (in my head) I have:
Data.csproj
references EF6 and handles Code First migrations
Models.csproj
references Automapper
refrences Data (above)
Services.csproj
references Models (above)
Web.csproj
references autofac
references services above
But I can't get my real project to look like that because
Identity sprinkles the model and EF references all over my Web.csproj
When I configure Autofac in Web.csproj and try to register my DbContexts and whatever other dependencies are in my other projects, I will need access to the concrete types, so Web will need to reference all other projects as the DI is setup in Web?
This is a brand new project auto-generated by the ASP .NET template. Thanks.
Generally, you avoid getting your Entity-Framework pollution into your web code by not referencing your data-models in your web project.
If you put interfaces for the models in a separate infrastructure project, for example, you won't have that problem any more. Your 'services' can return abstract types with no dependency on EF and coupling is reduced.
Personally, I like to get around this problem wither with a separate project that is responsible for factory code or (even better IMO) giving each project responsibility for constructing its own objects. Having the factory code in the same place further reduces coupling and can make refactoring easier.
One more thing...
If this is a new project, why do you even need a DI container. You could always use poor man's dependency injection and refactor later when you have a better idea of your needs. They are often overused or used as a crutch to hide overly complex lasagna code. It is an incredibly useful and powerful technology, but most of the benefit in terns of flexibility can also be realised through well designed factories and builders. These can have the additional benefit of increased readability.
I'm starting a new personal Prism 4 project. The Reference Implementation currently uses Unity.
I'd like to know if I should use MEF instead, or just keep to Unity.
I know a few discussions have mentioned that these two are different, and they do overlap, but will I be missing out if I simply choose Unity all the way?
Also check out the documentation:
Key Decision: Choosing a Dependency Injection Container
The Prism Library provides two options
for dependency injection containers:
Unity or MEF. Prism is extensible,
thereby allowing other containers to
be used instead with a little bit of
work. Both Unity and MEF provide the
same basic functionality for
dependency injection, even though they
work very differently.
Some of the capabilities provided by both containers include the following:
They both register types with the container.
They both register instances with the container.
They both imperatively create instances of registered types.
They both inject instances of registered types into constructors.
They both inject instances of registered types into properties.
They both have declarative attributes for marking types and dependencies that need to be managed.
They both resolve dependencies in an object graph.
Unity provides several
capabilities that MEF does not:
It resolves concrete types without registration.
It resolves open generics.
It uses interception to capture calls to objects and add additional functionality to the target object.
MEF provides several
capabilities that Unity does not:
It discovers assemblies in a directory.
It uses XAP file download and assembly discovery.
It recomposes properties and collections as new types are discovered.
It automatically exports derived types.
It is deployed with the .NET Framework.
I am currently doing the same investigation. I was last week attending the p&p symposium at Redmond. I had the chance to chat with some of the p&p people on that.
MEF
+Part of .net, no need for extra libraries
+Very powerful in extensibility, modularity scenarios
-More generic approach, less flexible for DI scenarios
-You need to decorate with attributes, your code is glued to MEF
Unity
+Very flexible for DI scenarios
+If you stick with ctor injection and avoid using named instances then you
don't need to use any attributes. Most
of your system doesn't rely on Unity
-No out of the box support for extensibility, modularity scenarios
-Need to deploy the 3rdparty libraries
What I think is a good idea is to use MEF for extensibility (manage the modules of your app, localize registrations) and use Unity for DI.
Well this has to be clear that MEF implements Inversion of control but it is not a part of it, so this means that they are not same, there is a difference, that we use unity when we have static dependency and MEF provides us with dynamic dependency.
MEF also provides us with extensibility, by which we can induce a port type mechanism and can also specigy the type of component which can interact via that port.
more can be understood from: MSDN Document
I'm working on an ASP.Net website along with a supporting Class Library for my Business Logic, Data Access code, etc.
I'm EXTREMELY new and unfamiliar with the Unity Framework and Dependency Injection as a whole. However, I've managed to get it working by following the source code for the ASP.NET 3.5 Portal Starter Kit on codeplex. But herein lies the problem:
The Class Library is setup with Unity and several of my classes have [Dependency] attributes on their properties (I'm exclusively using property setter injections for this). However, the Global.asax is telling Unity how to handle the injections....in the Class Library.
Is this best practice or should the Class Library be handle it's own injections so that I can re-use the library with other websites, webapps or applications? If that is indeed the case, where would the injection code go in this instance?
I'm not sure how clear the question is. Please let me know if I need to explain more.
Though not familiar with Unity (StructureMap user) The final mappings should live in the consuming application. You can have the dll you are using define those mappings, but you also want to be able to override them when needed. Like say you need an instance of IFoo, and you have one mapped in your Class Library, but you've added a new one to use that just lives in the website. Having the mappings defined in the site allows you to keep things loosely coupled, or else why are you using a DI container?
Personally I try and code things to facilitate an IOC container but never will try and force an IOC container into a project.
My solution breakdown goes roughly:
(Each one of these are projects).
Project.Domain
Project.Persistence.Implementation
Project.Services.Implementation
Project.DIInjectionRegistration
Project.ASPNetMVCFrontEnd (I use MVC, but it doesn't matter).
I try to maintain strict boundaries about projects references. The actual frontend project cannot contain any *.Implementation projects directly. (The *.implementation projects contain the actual implementations of the interfaces in domain in this case). So the ASPNetMVCFrontEnd has references to the Domain and the DIInjectionWhatever and to my DI container.
In the Project.DIInjectionWhatever I tie all the pieces together. So this project has all the references to the implementations and to the DI framework. It contains the code that does the registering of components. Autofac lets me breakdown component registration easily, so that's why I took this approach.
In the example here I don't have any references to the container in my implementation projects. There's nothing wrong with it, and if your implementation requires it, then go ahead.
I want to isolate all my code from the IoC container library that I have chosen (Unity). To do so, I created an IContainer interface that exposes Register() and Resolve(). I created a class called UnityContainerAdapter that implements IContainer and that wraps the real container. So only the assembly where UnityContainerAdapter is defined knows about the Unity library.
I have a leak in my isolation thought. Unity searches for attributes on a type's members to know where to inject the dependencies. Most IoC libraries I have seen also support that. The problem I have is that I want to use that feature but I don’t want my classes to have a dependency on the Unity specific attribute.
Do you have any suggestions on how to resolve this issue?
Ideally I would create my own [Dependency] attribute and use that one in my code. But I would need to tell the real container the search for my attribute instead of its own.
Check out the Common Service Locator project:
The Common Service Locator library
contains a shared interface for
service location which application and
framework developers can reference.
The library provides an abstraction
over IoC containers and service
locators. Using the library allows an
application to indirectly access the
capabilities without relying on hard
references. The hope is that using
this library, third-party applications
and frameworks can begin to leverage
IoC/Service Location without tying
themselves down to a specific
implementation.
Edit: This doesn't appear to solve your desire to use attribute-based declaration of dependency injection. You can either choose not to use it, or find a way to abstract the attributes to multiple injection libraries (like you mentioned).
That is the basic problem with declarative interfaces -- they are tied to a particular implementation.
Personally, I stick to constructor injection so I don't run into this issue.
I found the answer: Unity uses an extension to configure what they call "selector policies". To replace the attributes used by Unity, you just code your own version of the UnityDefaultStrategiesExtension class and register you own "selector policies" that use your own attributes.
See this post on the Unity codeplex site for details on how to do that.
I'm not sure that it's going to be easy to do the same if I switch to another IoC library but that solves my problem for now.
Couldn´t you just setup your configuration without the attributes, in xml. That makes it a bit more "unclear" I know, personally I use a combination of xml and attributes, but at least it "solves" your dependency on unity thing.
I have an ASP.NET MVC application which is using Linq to SQL classes placed in the Model folder.
I want to create some extra classes that I would normally place in my BLL but I'm not sure how to work this with MVC.
With WebForms I would have my DAL as a Class Library.
My BLL as a class library that referenced my BLL.
My Web Site that referenced both the DAL and BLL.
The problem I am facing is, if I create a class library, this will need to reference my MVC Application because it will need to use the types contained in my Model.
If I then add (or try to add) a reference to my class library, I will get a circular dependency.
In Web Forms. My other option would be to place the classes in the App_Code.
Is there an equivalent of App_Code in a MVC application?
You can move all your models to the class library, can't you? Neither MVC or VS mind. This would remove the dependency of the Models library on the Web app.
You can place that in the model folder. As all the business related classed are place into that folder
For better practice see the scottgu the nerddinner examples. He has created the respiratory classes in nerdinner application.
I agree in terms of the Model folder. You can organize it to your heart's content (BLL, DAL, etc.).
I personally would avoid doing a separate assembly unless you have a compelling reason to. Being the kind of developer that tends to over-complicate problems if I'm not careful, I try to follow the KISS (Keep It Simple Stupid) practices as much as possible, which tends to keep me out of a certain amount of trouble.
Try taking a look at S#arp Architecture. You can either use the template they provide or use it as a reference to help you make decisions.
http://code.google.com/p/sharp-architecture/