Implementing cross-cutting concepts into LOB/DI application - dependency-injection

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.

Related

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

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.

Why AOP and DI aren't used together very often

I am confused about this line
Aspect-Oriented Programming and Dependency Injection are very different concepts, but there are limited cases where they fit well together.
from this website
http://www.postsharp.net/blog/post/Aspect-Oriented-Programming-vs-Dependency-Injection
I understand the advantages of DI over AOP, but why aren't they used together more often? why are there only limited cases where they fit together? Is it because of the way AOP is compiled, that makes using both difficult?
How do you define "limited cases"? I myself always use AOP and DI together.
There are basically three ways to apply AOP, which are:
Using code weaving tools such as PostSharp.
Using dynamic interception tools such as Castle Dynamic Proxy.
Using decorators.
The use of DI with code weaving tools doesn't mix and match very well, and I think that's the reason that the Postsharp site states that "there are limited cases where they fit well together". One reason it doesn't mix and match is because Dependency Injection is about loose coupling, while code weaving hard couples your code and the aspects together at compile time. From a perspective of DI, code weaving becomes an anti-pattern. In section 11.2 of our book, Mark and I make this argument very clear. In summary we state:
The aim of DI is to manage Volatile Dependencies by introducing Seams into your application. Theis enables you to centralize the composition of your object graphs inside the Composition Root.
This is the complete opposite of hat you achieve when applying compile-time weaving: is causes Volatile Dependencies to be coupled to your code at compile-time. This makes it impossible to use proper DI techniques and to safely compose complete object graphs in the application's Composition Root. It's for this reason that we say that compile-time weaving is the opposite of DI–using compile-time weaving on Volatile Dependencies is an anti-pattern. [page 355]
If you use dynamic interception, however, which means applying cross-cutting concerns at runtime by generating decorators on the fly it works great with DI and it is integrated easily with most DI libraries out there, and can be done as well when using Pure DI, which is something we demonstrate in section 11.1.
My personal preference is to use decorators. My systems are designed around a few well defined generic abstractions, and this allows me to apply cross-cutting concerns at almost all places that are important to my system. That leaves me in very rare cases with a few spots where decorators don't work very well, but this is almost always caused by design flaws. Either by my own limitations as a developer or by design flaws in the .NET framework or some other tool. One famous design flaw is the INotifyPropertyChanged interface. You might have guessed it, but in our book we describe this method in a lot of detail. We spend a complete chapter (10) on this topic.

Zend Di vs ServiceManager dependency injection containers

What is DI for and what is its use case, when we have ServiceManager?
They appear to be similar since in configuration files for both zend-di and zend-servicemanager we can set up some options such as aliases and invokables.
I am trying to get a better understanding of what is happening behind the scenes with these components, and documentation did not give me enough info.
Could you please tell me what the difference is and when I should use Di instead of ServiceManager?
Zend\DI relies on magic, like reflections, to detect and inject dependencies while service manager uses user provided factories. That is main difference.
Di sort of deprecated in community in favor of SM due to complexity, debugging and performance issues.
It supposed to be good for RAD, but you need above average knowledge to use it properly.
On the other hand SM have pretty verbose and explicit wiring, you can open your code year later and easily figure out what is going on.
Zend\Di takes care of wiring your classes together, whereas with Zend\ServiceManager you have to wire things manually and write a factory closure for every class you want to instantiate.
Zend\ServiceManager is much faster since it does not rely on the slow Reflection API. On the other hand, writing closures for large applications with hundreds of classes becomes very tedious. Keeping your closures up-to-date will get trickier as your application grows.
To address this problem, I have written a Zend Framework 2 module called ZendDiCompiler. It relies on Zend\Di to scan your code and auto-generates factory code to instantiate your classes. You get the best of both components: the power of Zend\Di and the performance of Zend\ServiceManager.
I have put quite a bit of work into the documentation of ZendDiCompiler and some easy and more advanced usage examples are provided, too.
Basically the difference is as follows:
Zend\ZerviceManager = Factory driven IoC Container
Zend\Di = Autowiring IoC implementation
Zend\Di was Refactored for Version 3. Its behaviour now more solid and predictable than v2 and it is designed to integrate seamlessly into zend-servicemanager to provide auto-wiring capabilities (no more odd magic). Since it uses PHP's reflection api to resolve dependencies it is slower than a factory driven approach. Therefore version 3 comes with an AoT compiler to create a pre-resolved Injector that omits the use of Reflection. An additional benefit: The generated factories can also be used with Zend\ServiceManager directly.
There is a guide for using AoT with both components: https://zendframework.github.io/zend-di/cookbook/aot-guide/

.NET IoC container for mid-size ASP.NET MVC

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

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.

Resources