Unity, Autofac and probably quite a few other Dependency injection packages all support "keyed dependency injection containers" that allow to register multiple implementations of an interface and identify them uniquely via a key (be it a string, an int, an enum or whatever else).
However, .NET Core, so far I can see at least, doesn't have such a feature and if I were to try to implement anything like this, I'd have to do a workaround or find some hacky solutions for it. I am wondering, is there a particular reason this has not been introduced in .NET Core?
Unity example:
container.RegisterType<IService, ServiceImplementation1>("1");
container.RegisterType<IService, ServiceImplementation2>("2");
Autofac example:
builder.RegisterType<ServiceImplementation1>().Keyed<IService>("1");
builder.RegisterType<ServiceImplementation2>().Keyed<IService>("2");
...,is there a particular reason this has not been introduced in .NET Core?
Short answer: Yes
Reference Default service container replacement
The built-in service container is designed to serve the needs of the framework and most consumer apps. We recommend using the built-in container unless you need a specific feature that the built-in container doesn't support, such as:
Property injection
Injection based on name (a.k.a keyed)
Child containers
Custom lifetime management
Func support for lazy initialization
Convention-based registration
note: emphasis mine
Related
What are the required steps to use SimpleMembership (ASP.NET MVC 4) with RavenDB (or other databases) instead of SQL Server?
I am used to override the MembershipProvider but how does it work with the new SimpleMembership?
I saw there is a SimpleMembershipProvider so I think I should override it, but I don't know if the methods are for storing data purpose only or if they should contain business/validation logic)...
What about configuration? I know the InitializeDatabaseConnection method is normally responsible for initializing the whole shebang, but I don't think I should call it if I don't use Entity Framework.
Unfortunately, I did not find a lot of resources about the new SimpleMembership except two links which have not been very useful:
http://igambin.blogspot.ca/2012/08/simplemembershipprovider-huh.html
http://blog.osbornm.com/archive/2010/07/21/using-simplemembership-with-asp.net-webpages.aspx
So here is what I found after looking at some of the the source code (MVC4).
http://aspnetwebstack.codeplex.com/SourceControl/changeset/view/553690ac9488#src%2fWebMatrix.WebData%2fExtendedMembershipProvider.cs
SimpleMembership is an implementation of the abstract class ExtendedMembershipProvider.
The code inside SimpleMembership is mostly SQL operations and some calls to the underlying (called "previous" in the documentation) MembershipProvider.
I don't think it is of any use (in my case) to override SimpleMembership as its implementation is mostly tied to SQL Server. Instead, for what I understand, I should implement ExtendedMembershipProvider. Then, by setting this implementation in the web.config file, the WebSecurity helper would bypass SimpleMembership (default implementation) and call my implementation of the ExtendedMembershipProvider.
I don't think I will do this any soon since it looks even more complicated than before (more methods to implement)... but still doable.
However, all this said, I'm a bit disappointed that we still have to work with the MembershipProvider which, IMHO, is far (a lot of static and internal stuff) from the whole dependency injection thing that we love so much with ASP.Net MVC/WebApi.
Edit 1
This question was aked before Jon Galloway wrote this tutorial :
http://weblogs.asp.net/jgalloway/archive/2012/08/29/simplemembership-membership-providers-universal-providers-and-the-new-asp-net-4-5-web-forms-and-asp-net-mvc-4-templates.aspx
But my answer stays valid as this (taken from Jon Galloway article) resumes it:
Note that SimpleMembership still requires some flavor of SQL Server -
it won't work with MySQL, NoSQL databases, etc. You can take a look at
the code in WebMatrix.WebData.dll using a tool like ILSpy if you'd
like to see why - there are places where SQL Server specific SQL
statements are being executed, especially when creating and
initializing tables. It seems like you might be able to work with
another database if you created the tables separately, but I haven't
tried it and it's not supported at this point.
Here's my implementation for mongodb. Maybe it can help
https://github.com/malibeg/MongodbSimpleMembershipProvider#readme
SimpleMembership is not really meant to be used with the old MembershipProviders as it doesn't fullfill all of the same contracts that are assumed of normal MembershipProviders. Its mostly designed for use via the WebSecurity helper.
This link might be helpful for more info: Web Pages Tutorial
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 am Creating a new ASP.Net website "not mvc", and willing to make the data access layer has 2 versions, one using the Linq to Sql and another one using ad.net entity framework.
Note: kigg is doing the same but in MVC website and too complex than i want.
I learned that the best pattern to achieve my goal is using repository design pattern.
My question is, where in my code and layers "dal, bal, ui" the switch will happen? in other words where i will change the code to apply the linq to sql to ado.net entity framework or vice versa.
I wrote:
IRepository repository;
Then in the class constuctor
repository = MyRepositoryLinqToSql();
can some one teach me this part architecture wise?
If you want to create a pluggable architecture to be able to swap out the repository layer on the fly then you will need to create everything behind an interface and then use something like StructureMap to dynamically swap in what you need when you need it.
You would want to define a repository class like AccountRepository. One for linq to sql LSAccountRepository and EFAccountRepository. Both of these would inherit from IAccountRepository and have methods such as GetAccountByID, SaveAccount, DeleteAccount, etc.
Then using StructureMap you would have syntax like so to load the appropriate repository based on the system that you are loading in.
IAccountRepository _accountRepository = ObjectFactory.GetInstance();
Then via your configuration you can specify the default implementation of IAccountRepository and swap this out to point to either implementation at any time.
If this is too complex then a dependancy injection patten can be used in that you can have a method with a parameter of IAccountRepository. This method would be called by a controller (MVP or MVC) and you can pass in the appropriate reference at that time. This way you do not directly instantiate the repository inside of the method that might need one repository vs. another.
Even if you do decide to do a DI pattern you can still use StructureMap. When you instantiate an object that has other dependancies in it that StructureMap knows about (in the constructor) then StructureMap will also load up those objects as well. Then the caller of the object that has the method that you need will be the only loose coupling that is needed as StructureMap will dynamically take care of the dirty work for you.
This is a bit of a heavy question to answer, but you could add a constructor that takes an IRepository instance as a parameter and use that within the class itself. As for how to populate it, please do some research on Inversion of Control containers such as Spring and Windsor. These tools take configuration details about which specific implementations you want to use and then automatically pass these instances to the constructors and properties of classes.
For example, you can indicate which version of IRepository you want to use in your app.config file, and whereever this appears in a constructor an instance of your chosen class will be passed in.
I think you're looking for "Dependency Injection" solution.
Chack this out:
Unity Dependency Injection Video using ASP.NET Webforms - Ninject and Autofac IoC Too!
Unity And Asp.Net WebForms
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.