My team plan to start a new project this June. This application tend to used by 2,000 concurrent users. Now we are discussing about technical decision - what IoC container we will use in our project. All members in my team don't have experience with IoC, some of us read and know what it is though. Our requirements are:
Performance - Our management state that IoC may slow down the application and they expect that IoC container we use will not degrade the performance. They also expect the IoC container to have a good performance for little or large or resolver process.
Feature sets - I an my coworkers expect it to has rich feature sets. I don't know at this time what feature we gonna use but I have experience that some component can start easy but can't do something more advance.
Documents or books - I plan to study the IoC we selected by reading from online documents or books.
Work with ASP.NET MVC 4
I've used StructureMap, Autofac and Ninject. They are all very good.
I'd recommend using the CommonServiceLocator [http://commonservicelocator.codeplex.com] as part of your implementation. That way it is easy to change your mind later.
I personally like Autofac the best. It has a good balance of features and simplicity.
Supports Autowiring and assembly scanning
Lifetime Scoping (Such as Singleton or HttpRequest)
Easy to register an implementation to multiple request types
Supports Named or Keyed (named by Enum) registration
It's fast
http://code.google.com/p/autofac/wiki/MvcIntegration
http://nuget.org/packages/Autofac.CommonServiceLocator-unofficial
Related
Ironically, the problem DI is trying to solve, is exactly the problem that has been created in the project. Are there any resources for using the framework where i'm capable of picking and choosing which features I want to use/enable and those i want to omit?
It's very hard to manage dependencies and develop a modular and well-structured application without using dependency injection techniques.
Which i strongly disagree with; and believe to be the opposite, as there are plenty of cases where it's common without DI than with it.
Currently, i'm stuck on trying to use the project by calling all of the classes manually, as the DI is broken and constantly prone to errors, with vague or unhelpful exceptions being thrown and preventing app from executing. I'm unable to properly and thoroughly debug it, and that isnt the kind of assistance i'm seeking.
Strictly the question being posed is, i want to use the framework without using dependency injection, are there solutions; if yes, can you provide them in the form of step-by-step, or copy-paste? Can i use the framework without it, or am i tasked with writing my own because it's unable to keep it's functions modular?
My solution so far, is i'm attempting to restructure, the entire framework to remove the DI logic from the foundation of the framework (it's coupled inside [root] functions instead of beside them?); but i'm not sure if there are ways around it, and if possible to just strictly not use it if i dont want it enabled.
I've already created a repository class that's based on interface, then i've made some changes to a few manager classes that use the repository... but then there's stores, other managers (repetitive layers stacked inside each other), cache (not sure why it's layered into foundation), UoW (dont need this, cant null it out), publishers (dont know how to pull this one out), and a whole bunch of other, logic inside logic, that dont need to be structured the way the project is layered. The whole thing feels more like a Jenga tower, than a flexible framework where isolation of responsibilities is at core of development practice.
EDIT
Related StackOverFlow Problems:
AspNet Core3 Identity configuration
What i've attempted:
Multiple Identities in ASP.NET Core 2.0
ASP.NET Identity without Entity Framework
How to resolve generic interface to generic implementation when using dependency injection?
How to implement Unit Of Work pattern with Dapper? (used this to make Abp.UoW interface nullable, but there's still other areas of forced UoW logic in-between functions in core layers of framework)
Basically, any search results containing "without dbcontext", "without entityframework", "without dependency injection", "using dapper", that all contained "asp identity" were search queries i was using.
Before modification and after modifications (attempts at using my own app services and domain model) all yielded
An error occurred while starting the application.
AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Identity...
which is basically dependency injection breaking, and not being clear as to what the issue is, besides... "you cant use this class that inherits interface/abstract class that's referenced throughout framework and by DI." So i prefer not to use DI, and work around it, since solutions arent reliable to resolving my issues.
I hope I don't sound to pedantic, but your "without DI example" is still an example of DI. You apply constructor injection, which is a form of DI. What I understand is that you want to apply Pure DI instead of using the built-in DI Container. There are advantages of using Pure DI of using a DI Container, which is, for instance, described in:
When to use a DI Container by Mark Seemann,
When should you use a container? by me,
and about three quarters of our book on DI focuses on applying DI by hand, i.e. Pure DI.
Now for the bad news...
When working with ASP.NET Core (and most of the framework that depends on the .NET Core DI Container), you can never completely replace that DI Container with a Pure DI option. That shouldn't be a problem, however. Just think of ASP.NET Core's Container as its configuration system. Consider the simplistic configuration system of ASP.NET (classic) MVC; its configuration system consisted just of a large dictionary. Although you were able to replace services in the dictionary, you couldn't remove the dictionary all together. It was just too embedded with the system. The same holds with ASP.NET Core's configuration system. The whole framework completely depends on its existence. And chances are slim that Boilerplate allows you to work without it.
But there's some good news...
Even though you can't remove the built-in configuration system, you can choose to apply Pure DI to your own application components and if you wish, you could even go back to the old school tightly coupled code base if you really want (which I can see from your examples you don't, fortunately).
How to do this with ASP.NET Boilerplate exactly I can't tell, unfortunately. But the freely available code samples of my book do demonstrate this concept using ASP.NET Core MVC here and especially here.
I am currently creating a small personal windows (desktop) .NET LOB application and I want to use the opportunity to increase my knowledge and experience with DI. I've separated my application into model, DAO and GUI parts but I am wondering how to implement some cross-cutting concepts such as:
currently logged on user - used for:
asserting rights - in some parts of the application I check if the user has necessary rights
auditing - recording user actions into a separate database table
etc
current application parameters (loaded from configuration file or table) - used for:
defining business strategy
defining UI (theme for example)
etc
logging to file/database log - used for:
logging UI actions (clicking on buttons etc.)
logging business processes (results of calculations, strategy decisions etc.)
logging infrastructure stuff (SQL used to for CRUD operations)
etc
At the moment I can think of several ways to provide this information:
Using static properties - UserEntity.Current, Configuration.Current, Logger.Current, etc.
Pros:
Simple to implement
Simple to use
Cons:
Gets messy
It is unclear which part of the application uses what
Can not be used if you need finer granularity (for example if for some processes in the application you need to override current values)
Using DI - giving each class which needs this information a property/ctor parameter
Pros:
It is clear for each class what it needs
It is easy to unit test
Cons:
It just seems to explode constructors
Makes problems if class needs to have a default constructors
Difficult to setup when classes get instantiated by 3rd party (XAML)
Using ServiceLocator
Pros:
Easy to setup
Easy to use
Cons:
It is unclear which part of the application uses what
Difficult to setup finer granularity (but not impossible)
I am currently leaning towards ServiceLocator as I've worked with it before and it worked quite nice. However I am concerned about loss of control. It gets very easy to just reach for the service locator instead of trying to fix a design problem.
Can somebody provide their experiences/knowledge?
Sounds like perfect case to start with aspect-oriented approach. Your application's LOB will be designed according to business functional requirements that has been cross-cutted with different non-functional requirements: authentication, audit, logging, etc.
In same time, some of current application requirements could be solved by dependency-injection. To start, I recommend first to identify composition root. For example, in wpf applications itβs the Application.OnStartup method. In case if you are able to identify composition root it is better to avoid service-locator. Service locator will add unneeded complexity while maintaining and testing, because it could resolve literally anything, thus dependency management will be complicated.
Next step, to decide: should dependency injection and aspect-oriented approaches be separated or combined. Both approaches has benefits and drawbacks.
While choosing separated approach you could use postsharp with a lot of benefits: great samples and documentation, community and ready to use aspects. But nothing come for free, postsharp has only limited number of features in free version and complicated integration with continues-integration.
Another solution: combine dependency-injection with dynamic-proxy. As long as you follow conception: program to an interface, not an implementation β you will achieve all requirements. Benefits: one place to wire all components. There are two major drawbacks: first dynamic proxy is quite limited itself, second β integration between dependency injection container and dynamic proxy β for some container it already exists, for others not. Example: Ninject extension Interception, or StructureMap and Interception.
I recommend you to take a look at following resources to find more answers yourself:
* Book AOP in .NET: Practical Aspect-Oriented Programming by Matthew D. Groves: first chapter available for free
* Book Dependency Injection in .NET by Mark Seemann: well-written book about dependency injection, and chapter #9 dedicated to interception, approach that I found quite useful in cases that you had described in question. Author of book also has an excellent blog dedicated to dependency injection and video about aspect-oriented programming with dependency Injection.
I am going to use it in a project with less-experienced developers so a complex framework such as Spring.NET is not an option. I was thinking about:
Ninject
Castle Windsor
StructureMap
Which would present a moderate learning curve without losing flexibility?
and another question - where is the correct place to put the configuration? Since the kernel/configuration on a 3-tier ASP.NET application (not MVC!!! all examples are using MVC :) )
The great thing about proper use of DI is that you can defer the decision about which DI Container to use until the last responsible moment. In application architecture terms, this corresponds to a so-called Composition Root, which is where you wire all depedendencies together. This is often the application's entry point.
Apart from the Composition Root, the entire application can be written without referencing any particular DI Container at all. You just need to follow well-known patterns and principles.
When it comes to pick a DI Container, I'm aware of these DI Containers for .NET:
Castle Windsor
StructureMap
Unity
Autofac
Ninject
Spring.NET
Personally, I have been happy with Castle Windsor so far, but I have yet to gain extensive experience with all of these containers.
Here's an ASP.NET (not MVC) Ninject sample:
http://davidhayden.com/blog/dave/archive/2008/06/20/NinjectDependencyInjectionASPNETWebPagesSample.aspx
I have used ninject and found it easy to bring new developers up to speed with it.
Consider to start with wiring by hand: see http://blog.objectmentor.com/articles/2010/01/17/dependency-injection-inversion . It gives less-experienced developers a better insight in the basics of IOC/DI.
I think you are being too hasty to reject spring.net. Spring offers an extremely flexible learning curve, so at the beginning it's kind of "you take what you want from it" approach.
You can start with the simplest-of-all IoC container, and later on move to aop, transactions, unit testing, or whatever you desire, so the complexity builds up gradually.
This was the #1 selling point at my last two jobs for using Spring. Additional points were:
It doesn't force you to use its api or to bend your architecture. Again, this leads you to adapt its features at your own pace.
Very extensive documentation.
When the project matures, so will your developers, so spring will come out handy at the end ... (at no cost in the beginning, in my opinion)
Autofac is my container of choice. It allows registration via lambda expressions for maximum flexibility (the link has some nice examples).
It also has a Silverlight-compatible version. I'm unsure if the other containers do.
As for placement, the container should be built during application startup. For an ASP.NET application, this would be in the Global.Application_Start method.
Autofac has ASP.NET integration which injects pages instances using the container you build during startup.
Have a look at http://funq.codeplex.com/ first of all it's extremely fast compared to windsor and other reflection based containers second of all it's very flexible but still has a very readable configuration (If you've gotten your head around Lamba expressions which should take to long any ways)
We use the managed extensibility framework. It is part of the .NET 4.0 framework (currently in release candidate), where you can find it in the System.ComponentModel.Composition namespace. The codeplex site is currently still the best source of documentation.
The focus of MEF is more on "extensibility" rather than "dependency injection", but it uses dependency injection to achieve this. For example, the visual studio 2010 code editor uses MEF to enable extensibility.
We use it as a DI framework and have not yet run into any problems (though I did need the dynamic instantiation sample which is not part of the core yet).
If you're yet familiar with any DI framework, I'd go with the Simple Injector.
It has a very simple API, that will get you started very quickly. Although simple, it still enables many advanced configuration scenario's. The library designed with migration in mind, which means that switching to another framework would is rather straightforward. To prove this point, there is an migration guide on the project's wiki.
In addition to Ninject, which is a great product, there are also two other options that I'm familiar with:
Microsoft's Unity. Some Alt.NET folks think it's a little on the big & complicated side. I've been using it for several months now as part of Prism (Prism is NOT required to use Unity. It's available stand-alone) and I've found it to be simple and straight-forward.
StructureMap. I've found StructureMap to also have a very gentle learning curve with fast ramp up.
Hope this helps.
I find StructureMap very usefull and intuitive to use. I played with Ninject a bit and found that less convenient, but YMMV. I would also recommend you use the common service locator as an intermediary between the actual implementation of your IOC and your application. When you want to switch your IOC/DI container later on, this is less painfull. There are adapters for StructureMap and Castle windsor. And I think from googling that there also is an adapter for Ninject 2 according to this blog.
I have a solution with two relevant (to this question) projects, and a few others;
Class library with functionality used by several other projects.
ASP.NET MVC application.
My question is basically where I should do IoC with Ninject 2, considering...
The class library needs some DI love, among other things in the repository classes which need web request specific session objects (think Unit of Work).
The MVC app needs DI since with Ninject 2 you basically inherit from NinjectHttpApplication.
Unit tests for the class library need to be aware of this to inject a different set of repositories.
Unit tests for the web app need to be injected for the same reason.
I have painted myself into a mental corner here, because I only saw three options to begin with. DI in the class library, DI in the web app, or both, but there are problems with each:
I can't do DI only in the class library since the MVC app needs to inherit from NinjectHttpApplication to begin with.
I can't do DI only in the MVC app - the class library is used by other libraries, after all, and the MVC app shouldn't know too much about the internals of the library anyway.
I guess this is the only way out I can see: Independent IoC for both projects. The class library and the MVC app each have their own IoC setup and do DI for their stuff without really caring about each other.
Does anyone have some "best practices" or guidelines on how to do something like this? I can't imagine I'm the first person to end up in this situation, and it would sure be nice to know what the "proper" way to do this is...
Thanks!
I don't know NInject, but unless it works vastly different than Windsor, StructureMap etc. the answers tend to stay the same, as there are some common DI patterns. With that in mind:
The first thing to realize is that DI isn't tied to a particular framework such as NInject or Windsor. It is a set of techniques and design patterns to follow. You can do DI manually using so-called Poor Man's DI, but obviously it gets much better with a DI Container.
Why is this relevant? It is relevant because once you realize this, the corollary is that the vast majority of your application's code should have no knowledge of the DI Container whatsover.
So where do you use the DI Container? It should only be used in a Composition Root, which in your case would correspond to Global.asax. You can read a bit more about this in this SO answer - although that question is about Windsor, the principle remains the same.
How about your unit tests then? They should be completely ignorant of the DI Container as well. See this other SO answer for more details.
DI can be achieved in your library with copious use of Constructor Injection. You don't need to reference any DI Container to do that, but it makes life a lot easier if you use a DI Container to resolve all dependencies from the Composition Root.
What is an IoC container?
What is an IoC/DI framework?
Why do we need a framework for IoC/DI?
Is there any relationship between IoC/DI and AOP?
What is Spring.net/ninject with respect to IoC and AOP?
JMSA,
James Kovacs wrote a fantastic article which covers many of your questions I would recommend reading it Here
Spring.Net, Ninject, Unity, Castle Windsor, Autofac are all IOC containers which are configurable in different ways, many of them do also support AOP.
Frameworks for IOC/DI are useful because they provide standard mechanisms, for example if you are hiring a new developer it is much easier to say, we use this framework and pass them the links to the tutorials / help guide. At the same time these frameworks are tried and tested by a large community / companies.
Let me know if any of your questions remain unanswered after reading the article and the above answes and I'll do my best to provide further assistance.
From a semantics point of view...
Dependency Injection itself implies a dependency, i.e. something that is required for construction/use (the application's "core concerns"). For example, a car is not a car without an engine.
Aspects are described as being cross-cutting to the application's core concerns. That means both separate from and non-crucial to the core concerns (you could think of them as "nice-to-haves"). Since the application can run without aspects, are they really dependencies? For example, a car is still a car even without an immobiliser.
(Of course, this is from a theoretical standpoint. In the real world matters like security are often as crucial to the existence of a marketable product as the core concerns themselves.)
So in while in practice DI can be used to implement aspects, I would not call that process true DI. This is coming from someone who uses constructor injection exclusively.
Martin Fowler has a good article here on the meaning of Inversion of Control and Dependency Injection.
Spring.NET usage AOP is described in detail here. I'm more familiar with the Java-based version of Spring, so I cannot say with absolutely certainty that Spring.NET currently only supports proxy-based AOP.
That is, a class to be advised must implement an interface. Spring will create a dynamic proxy that implements this interface and delegates to the original target instance.
Although it does state:
In a future release we will implement proxies using inheritance, which will allow you to proxy classes without interfaces as well and will remove some of the remaining raw reference issues that cannot be solved using composition-based proxies.