Using ASP.NET Boilerplate without Dependency Injection (DI) Container? - dependency-injection

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.

Related

How best to organise my Visual Studio solution for Unit Tests and Dependency Injection

I have a fresh Visual Studio 2012 solution which consists of the following projects:
x1 Asp.Net Web API project (This holds my MVC/API controllers)
x1 Services project (based on the ASP.NET Empty Web Application template)
I've created two additional projects for the above (based on the ASP.NET Empty Web Application template) which I've labelled as my test projects.
I'm slowly getting my head around the whole TDD and DI approach to development hence my brain is a little swiss cheesed at this late hour.
I would like guidance on where I should setup DI and my unit tests. The approach I'm taking is to put as many of my methods in to my 'services' project. My main Web API project has a reference to my services project, so I can access all my public methods from that class library (I think that's the correct terminology).
I've now hit a brain block! I want to unit test as much as possible all the methods I expose in my services project. However my DI container (Castle Windsor) is only setup in my main API project, given that it has controllers etc.
So question:
For my services project do I just forget DI and write my unit tests direct to the concrete classes/interfaces? The reason I ask is because the Castle Windsor examples I've seen have been around setting up a container for my controllers/MVC web application and then instantiating the container via the application startup in global.ascx. If I should be using DI in my services project, how would I instantiate a container and where?
Following on from question 1, I wanted to gauge peoples opinions on where/how to structure all my unit tests. The easiest place to stick my tests would be in my main Web API project, given that everything I'm doing is either directly coded in that project or pulled in as a reference (my services project in this case).
That said I would imagine it would be better to have tests written exclusively for my services project, of which are contained in their own project. That way I can test my methods without the Web API project being involved at any level. Who knows, the Web API project might get canned but the services project is recycled for a different platform (hopefully you can see where I'm going with this).
The end goal of all this is to have most of my methods held in a services project, reusable for other projects in whatever form they may come. To have my Web API and other future MVC web applications pull functionality from my services library. All the while I have maintainable, manageable and above all 'testable' projects.
I'm at the start of my development cycle and doing all that I can in reading articles and reaching out to those in the know to get best advise so I can create solid foundations for my project.
To answer your questions: use an IOC container like Castle Windsor where you wire up your components. If you don't wire up components in your services project, there's no need for an IOC container there. It IS however a good idea to apply DI in your services project.
Sidebar: I think you might be confusing DI with IOC containers: DI is just a principle that states that you don't just "new up" dependencies, but rather asks them nicely (through a constructor, setter, whatever). IOC containers are a step further and will do much of the heavy lifting once manually managing your dependencies becomes a burden. I like to handwrite my unit tests and NOT use a container like castle windsor there so I really feel the pain of having too many dependencies in a class and can do something about that smell instead of having the container act like a deodorant. There are some cases where I make an exception and do use an IOC container in my unit tests, for example for legacy code with huuuuuge lists of difficult dependencies.
On your unit test question: some people like to stick them in the same project. I personally like to put them in a separate project that only contains tests so I can't "cheat". By cheating I mean the following: one of the reasons to write unit tests is to highlight painful parts in your code (this is what's called "listening to your tests"). By putting tests in the same project as your production code you can more easily reach into the internals of your objects (through the "internal" visibility keyword, for example). That's almost always a design smell and this smell is made more clear when your tests can't access your production code through its internals and have to use the public API.
Finally: it's super awesome that you're thinking about this stuff at the start of your project. This is when it's easiest to introduce practices like unit testing because you don't have a large -untestable- legacy codebase yet. Don't give up, it's definitely worth the effort once you get the hang of it!
You wire up your IOC container during application startup. Generally speaking, the code that initialises the container should be the only production code that knows what container you’re using. There can be exceptions, but they should be few and far between. Since you’re creating a binary dependency between your MVC project and your service project, you should only have a single container, created in your MVC project.
There are two main approaches you can follow for setting up your container. You can either setup all of your mappings/mapping rules within the MVC project, or you can split the responsibility so that your MVC project calls out to each library it depends on with the library having responsibility for the mappings within it. Which approach is best, is going to depend on various things including the complexity of your required mappings.
As I’ve said, with either approach to registering your mappings, the majority of your code shouldn’t know about your IOC. You should be writing your code to depend upon interfaces, which in production will be injected in by your container. When you are writing your unit tests then you get to decide what it makes the most sense to inject. Depending what you’re trying to test, you can then inject a real dependency or a Mocked/Stubbed dependency in order to allow you to have more control over the flow through your code under test.
I would strongly recommend not putting your tests in the same project as your production code. Whilst it may be slightly easier to get it up and running, it comes with some downsides / risks. Your assembly will need to add references to anything that your tests rely on (testing frameworks, mocking frameworks etc.). The last thing I would want to do is deploy test code to a production server, at the very least it adds bulk to your binary at worst it introduces security vulnerabilities. You also run the risk of accidently creating a dependency on one of your test classes (such as a helper method). If you put your tests in a separate class library that depends on your production code then these dependency issues go away.
I tend to create a unit test project for each production project. Depending on what I’m writing, I might make use of the InternalsVisibleTo property to allow my test project to see internal classes. I might also create one or more integration test projects. Having an integration test project that uses something like Selenium would allow you to validate that your MVC project actually works end to end which is an important aspect of testing to consider. It’s very easy to get carried away with dependency injection and unit testing. You write a whole bunch of code, paired with unit tests and then it falls over when you run it for the first time because you haven’t set your container up properly.

Implementing cross-cutting concepts into LOB/DI application

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 looking for a simple yet practical and robust IOC/DI framework for .net

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.

IoC, AOP and more

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.

IoC Container Configuration/Registration

I absolutely need to use an IoC container for decoupling dependencies in an ever increasingly complex system of enterprise services. The issue I am facing is one related to configuration (a.k.a. registration). We currently have 4 different environments -- development to production and in between. These environments have numerous configurations that slightly vary from environment to environment; however, in all cases that I can currently think of, dependencies between components do not differ from environment to environment, though I could have missed something and/or this could obviously change.
So, the ultimate question is, does anybody have a similar experience using an IoC framework? Or, can anybody recommend one framework over another that would provide flexible registration be it through some sort of convention or simplified configuration information? Would I still be able to benefit from a fluent interface or am I stuck with XML -- I'd like to avoid XML-hell.
Edit: This is a .Net environment and I have been looking at Windsor, Ninject and Autofac. They all seem to now support both methods of registration (fluent and XML), though Autofac's support for lambda expressions seems to be a little different than the others. Anybody use that in a similar multi-deployment environment?
If you want to abstract your container, and be able to use different ones, look into having it injectable in a way I tried to do it here
I use Ninject. I like the fact that I don't have to use Xml to configure the dependencies. I can just use straight up C# code. There are multiple ways of doing it also. I know other libraries have that feature, but Ninject offers fast instantiation, it is pretty lightweight, it has conditional binding, supports compact framework, and it supports Silverlight, 2.0. I also use a wrapper on top of it, in case I do switch it out for another framework in the future. You should definitely try Ninject when deciding on a framework.
I'm not sure whether it will suit your particular case, you didn't mention what platform you're working in, but I've had great success with Castle Windsor's IOC framework. The dependencies are setup in the config file (it's a .NET framework)
Look at Ayendes rhino commons. He uses an abstraction over the IoC container. So that you can switch containers whenever you want. Something like container.Resolve is always there in every container.
I use Structuremap to do the dirty work it has a fluent interface and the XML things and it is powerfull enough for most things you want to do. Each one has it's own pros and cons so a little abstraction so you can easily switch (you never know how long they are going to be around) is good. For the rest I think Spring.Net, Castle windsor, Ninject and StructureMap aren't that far apart anymore.

Resources