I have a asp.net mvc app where a lot of things are dependent on knowing the url of the web request (it's multi-tenant). Currently the HttpContext is being injected in a lot of constructors (through a wrapper that sets up some variables based on the context) using Simple Injector. This means that most things have to be instanced "per web request" vs per application.
Now what I could do here is just pass the HttpContext wrapper, or only the required data, in methods rather that constructor injection.
What I would like some clue on is the actual performance difference. Because it does make it a lot less elegant having to always pass the wrapper/data. This is however a quite high-traffic site so I will definitely consider changing it up.
I do realize this depends a bit on what's going on in the constructor, but assume that all it does is assign dependencies.
To clarify I do not have a specific performance problem. This is only optimization and I'm wondering if it's worth going through the work of refactoring to achieve this.
Instead of just a wrapper you can place a provider in between, which you could be singleton, which makes it possible for all consumers to be singleton as well.
Like this:
public interface IHttpContextProvider
{
HttpContext CurrentContext { get; }
}
public class HttpContextProvider : IHttpContextProvider
{
public HttpContext CurrentContext => HttpContext.Current;
}
public interface IMyContextWrapper
{
string CurrentRoute { get; }
}
public class MyContextWrapper : IMyContextWrapper
{
private readonly IHttpContextProvider httpContextProvider;
public MyContextWrapper(IHttpContextProvider httpContextProvider)
{
this.httpContextProvider = httpContextProvider;
}
public string CurrentRoute
{
get
{
var context = this.httpContextProvider.CurrentContext;
return informationFromContext;
}
}
}
I'd be tempted to stick with constructor injection because it clearly shows the dependency. It's true that there could be a small performance hit because you have to use per-web-request, and that will involve more garbage collection than if you pass the context as a parameter. But, has it yet become a problem?
If you find this is a performance problem, you could look at a third option providing your tenant count is not enormous. You could instantiate and re-use a pool of singleton classes, where one is configured per tenant.
I've built a multi-tenant site and have certain services that need to be created for every web request, and definitely haven't had performance problems in that area.
Related
I'd like to know how to register the classes and setup a Simple Injector container to instantiate the classes in the following way. ie go from manual DI to having the below Consumer class have the CompositeService injected and the object graph and lifetimes setup as follows:
To bring some context (if it helps) the Consumer class might be a ViewModel from a WPF application which gets instantiated when the View is requested.
public class Consumer
{
public Consumer()
{
var sharedSvc = new SharedService();
var productSvc = new ProductService(sharedSvc, new MathHelper());
var compositeSvc = new CompositeService(sharedSvc, productSvc, new MathHelper());
compositeSvc.Process();
}
}
where:
MyContext should be shared within the scope of the calls.
ProductService and CompositeService can be transient or shared within the scope.
MathHelper must be transient.
Q: How can the above be achieved with Simple Injector?
OR more specifically:
How can I instantiate multiple MathHelpers within the context of the Simple Injector Scope?
I've read up on http://simpleinjector.readthedocs.org/en/latest/lifetimes.html
and read and followed the SO answer https://stackoverflow.com/a/29808487/625113 however,
it seems either everything can be transient or scoped but not certain specific objects scoped and the rest transient (which seems odd).
Update 1
The following with Simple Injector will achieve the SharedService result, but if I want ProductService and CompositeService to also have a scoped lifetime it wont work:
cont.RegisterLifetimeScope<SharedService>();
cont.Register<MathHelper>();
cont.Register<ProductService>();
cont.Register<CompositeService>();
using (cont.BeginLifetimeScope())
{
var compositeSvc = cont.GetInstance<CompositeService>();
compositeSvc.Process();
}
If I register either or both of the ProductService or CompositeService as RegisterLifetimeScope I get a Lifetime mismatch exception. ie
cont.RegisterLifetimeScope<SharedService>();
cont.Register<MathHelper>();
cont.RegisterLifetimeScope<ProductService>();
cont.Register<CompositeService>(); // or cont.RegisterLifetimeScope<CompositeService>();
using (cont.BeginLifetimeScope())
{
var compositeSvc = cont.GetInstance<CompositeService>(); // Exception thrown
compositeSvc.Process();
}
Throws an exception leading to this page: https://simpleinjector.readthedocs.org/en/latest/LifestyleMismatches.html
I can under that in relation to Singleton should be dependent on Transient and can infer a sort of understanding that the same could be said in this case that Simple Injector is warning that Scoped can't depend on Transient because Transient isn't managed within the scope.
So my question is more specifically how can I instantiate multiple MathHelpers within the context of the Simple Injector Scope?
Update 2 - Further background and example
Brief background - This situation arose as I have a 4 year old, 2-tier, WPF based application currently using Ninject which has the bloated mixed Service architecture that #Steven describes
in his blog series (ie the Services have become a mash of mixed, semi-related, command and queries). Most of these services are a good candidate for separating out into
ICommandHandler/IQueryHandler architecture...but you can't do things overnight, so first crack was to convert from Ninject to SimpleInjector (yes I know Ninject can do the same thing in regards to this architecture
but there are other reasons for moving to SimpleInjector).
As far as "scoping" the dependency resolution, a "scope" (in this application) is considered to be for the life of a form so one DbContext (like the SharedService in the example above) is shared amoungst the
services that the form/viewModel require and MOST of the services are per scope with some injected services or helper classes needing to be injected as Transient.
This (to me) is analogous to Mark Seemann's hand-coded example from http://blog.ploeh.dk/2014/06/03/compile-time-lifetime-matching/ where he has a Per Request (singleton-scoped) service which has
Transient objects injected into it.
Edit: I had misread Mark Seemann's example and was reading the code as if the BarController were a service. So whilst the BarController object composition is the same the lifetime is not. That said the SomeThreadUnsafeService could just as easily have a new SomeServiceThatMustBeTransient injected into it but, I stand corrected, his example doesn't do this.
Hence I was wanting to know how to do the object composition Mark Seemann does in Simple Injector but outside the context of web reqeusts (my assumption is that Simple Injector's
Per web request scoping is in essence a specific type of Lifetime Scoping).
To address #Steve and #Ric .net's comment and answer, I can see that there is the potential to end up with the scenario where 2 different services use another, shared service that uses a transient object (storing state) and the supposedly transient object becomes a
Singleton Scoped object in the context of "some" of those services. eg
public class SingletonScopedService1
{
private readonly TransientX _transientA;
public SingletonScopedService1(TransientX transientA)
{
_transientA = transientA;
}
public void PokeTransient()
{
_transientA.Poke();
}
}
public class SingletonScopedService2
{
private readonly SingletonScopedService1 _service1;
private readonly TransientX _transientB;
public SingletonScopedService2(SingletonScopedService1 service1, TransientX transientB)
{
_service1 = service1;
_transientB = transientB;
}
public void GoFishing()
{
_service1.PokeTransient();
// This TransientX instance isn't affected
_transientB.Poke();
}
}
public class SingletonService3
{
private readonly SingletonScopedService1 _service1;
public SingletonService3(SingletonScopedService1 service1)
{
_service1 = service1;
}
public void DoSomething()
{
_service1.PokeTransient();
}
}
If DoSomething() is called on SingletonScopedService3 and GoFishing() is called on SingletonScopedService2 (and assuming TransientX maintains state) then results "may" be unexpected depending on the purpose of TransientX.
So I'm happy to accept this since the application is operating as expected (but also accept that the current composition is fragile).
With that said, can my original composition or Mark Seemann's example be registered with Simple Injector with the required life-times or is it strictly not possible by design and better to manually compose the object
graph (or inject a Func as #Ric .net suggests) for the instances where this is required until further refactoring/hardening can be done?
Update 3 - Conclusion
Whilst Ninject allows you to register my original composition like:
var kernel = new StandardKernel();
kernel.Bind<SharedService>().ToSelf().InCallScope();
kernel.Bind<MathHelper>().ToSelf();
kernel.Bind<ProductService>().ToSelf().InCallScope();
kernel.Bind<CompositeService>().ToSelf().InCallScope();
Simple Injector by design does not and I believe my second example is an example as to why.
FYI: In my real-world case, for the few instances that the object graph had this, I've manually constructed the graph (just to get switched to Simple Injector) with the intent on refactoring these potential issues out.
As explained in the linked SO question what the Lifestyle Mismatch exception is basically saying is that you're creating a so called captive dependency when you let a object depend on another object which has a shorter lifestyle.
While it maybe sounds odd to you, a captive dependency is:
A real life problem which, if undetected, would typically lead to very strange bugs which are very hard to debug
A sign, as indicated by Steven, that the service has some kind of state which is never a good sign
If MathHelper has mutable state and therefore needs to be injected in other services as transient, MathHelper has become some sort of 'runtime data'. And injecting runtime data is an anti-pattern.
This blogpost describes in detail what the problem is with runtime data and how to solve this. Solving your problem as described there is the way to go!
Because you did not specify the implementation details of MathHelper, it is hard to give you some advice how you should refactor MathHelper. So the only advice I can give you is, let runtime data or 'state' flow through the system as messages. You can read about message based design here and here.
There are however several other options, which will work but aren't good design IMO. So the advice is not to use these, but to be complete:
Instead of injecting MathHelper as a transient you could inject a MathHelperProvider or even simpler inject a Func<MathHelper> which you could register as singleton:
container.RegisterSingleton<Func<MathHelper>>(() => container.GetInstance<MathHelper>());
Notice that by registering a delegate you will make the container blind. It won't be able to warn you of misconfigurations in this part of the object graph anymore.
The other solutions I had in mind are so ugly in its design, that after writing them, I decided to leave them out of this answer!
If you would add some details about why MathHelper needs to be transient, I could give you some advice where you could make adjustments to make it scoped or even better: singleton.
There seems to be a stigma on SO regarding use of Singletons. I've never personally bought into it but for the sake of open mindedness I'm attempting to give IoC concepts a try as an alternative because I'm frankly bored with my everyday work and would like to try something different. Forgive me if my interpretation of IoC concepts are incorrect or misguided.
Here's the situation: I'm building a simple HttpListener based web server in a windows service that utilizes a plug-in model to determine how a request should be handled based on the URL requested (just like everyone else that asks about HttpListener). My approach to discovering the plug-ins is to query a configured directory for assemblies decorated with a HttpModuleAssemblyAttribute. These assemblies can contain 0 or more IHttpModule children who in addition are decorated with a HttpModuleAttribute used to specify the module's name, version, human readable description and various other information. Something like:
[HttpModule(/*Some property values that matter */)]
public class SimpleHttpModule : IHttpModule
{
public void Execute(HttpListenerContext context)
{
/* Do Something Special */
}
}
When an HttpModule is discovered I would typically add it to a Dictionary<string, Type> object who's sole purpose is to keep track of which modules we know about. This dictionary would typically live in my variety of a Singleton which takes on the persona of an ACE style Singleton (a legacy from my C++ days where I learned about Singletons).
Now what I am trying to implement is something similar using (my understanding of) general IoC concepts. Basically what I have is an AppService collection where IAppService is defined as:
public interface IAppService : IDisposable
{
void Initialize();
}
And my plug-in AppService would look something like:
[AppService("Plugins")]
internal class PluginAppService : IAppService, IDictionary<string, Type>
{
/* Common IDictionary Implementation consisting of something like: */
internal Type Item(string modName)
{
Type modType;
if (!this.TryGetValue(modName, out modType)
return null;
return modType;
}
internal void Initialize()
{
// Find internal and external plug-ins and add them to myself
}
// IDisposable clean up method that attempts to dispose all known plug-ins
}
Then during service OnStart I instantiate an instance of AppServices which is locally known but passed to the constructor of all instantiated plug-ins:
public class AppServices : IDisposable, IDictionary<string, IAppService>
{
/* Simple implementation of IDictionary */
public void Initialization()
{
// Find internal IAppService implementations, instantiate them (passing this as a constructor parameter), initialize them and add them to this.
// Somewhere in there would be something like
Add(appSvcName, appSvc);
}
}
Our once single method implementation becomes an abstract implementation + a constructor on the child:
[HttpModule(/*Some property values that matter */)]
public abstract class HttpModule : IHttpModule
{
protected AppServices appServices = null;
public HttpModule(AppServices services)
{
appServices = services;
}
public abstract void Execute(HttpListenerContext context);
}
[HttpModule(/*Some property values that matter */)]
public class SimpleHttpModule : HttpModule
{
public SimpleHttpModule(AppServices services) : base(services) { }
public override void Execute(HttpListenerContext context)
{
/* Do Something Special */
}
}
And any access to commonly used application services becomes:
var plugType = appServices["Plugins"][plugName];
rather than:
var plugType = PluginManager.Instance[plugName];
Am I missing some basic IoC concept here that would simplify this all or is there really a benefit to all of this additional code? In my world, Singletons are simple creatures that allow code throughout a program to access needed (relatively static) information (in this case types).
To pose the questions more explicitly:
Is this a valid implementation of a Factory Singleton translated to IoC/DI concepts?
If it is, where is the payback/benefit for the additional code required and imposition of a seemingly more clunky API?
IoC is a generic term. Dependency Injection is the more preferred term these days.
Dependency Injection really shines in several circumstances. First, it defines a more testable architecture than solutions that have hard-coded instantiations of dependencies. Singletons are difficult to unit test because they are static, and static data cannot be "unloaded".
Second, Dependency Injection not only instantiates the type you want, but all dependant types. Thus, if class A needs class B, and class B needs class C and D, then a good DI framework will automatically create all dependencies, and control their lifetimes (for instance, making them live for the lifetime of a single web request).
DI Containers can be though of as generic factories that can instantiate any kind of object (so long as it's properly configured and meets the requirments of the DI framework). So you don't have to write a custom factory.
Like with any generic solution, it's designed to give 90% of the use cases what they need. Sure, you could create a hand crafted custom linked list data structure every time you need a collection, but 90=% of the time a generic one will work just fine. The same is true of DI and Custom Factories.
IoC becomes more interesting when you get round to writing unit tests. Sorry to answer a question with more questions, but... What would the unit tests look like for both of your implementations? Would you be able to unit test classes that used the PluginManager without looking up assemblies from disk?
EDIT
Just because you can achieve the same functionality with singletons doesn't mean it's as easy to maintain. By using IoC (at least this style with constructors) you're explicitly stating the dependencies an object has. By using singletons that information is hidden within the class. It also makes it harder to replace those dependencies with alternate implementations.
So, with a singleton PluginManager it would difficult to test your HTTP server with mock plugins, rather it looking them up from some location on disk. With the IoC version, you could pass around an alternate version of the IAppService that just looks the plugins up from a pre-populated Dictionary.
While I'm still not really convinced that IoC/DI is better in this situation, I definitely have seen benefit as the project's scope crept. For things like logging and configurability it most certainly is the right approach.
I look forward to experimenting with it more in future projects.
I have a User entity which has a HasCompletedSecurity property which indicates whether that particular User has answered the number of security questions required by the system. The number of security questions the system requires is configurable and retrieved from a config file. How should the User class access the configured information?
I currently have an IConfigurationService interface behind which I have implementations which use the ConfigurationManager or the Azure equivalent if it is available. I've encapsulated access to my DI container through a static InjectionService class, and am currently resolving the configured value like so:
public class User
{
private static readonly IConfigurationService _configurationService =
InjectionService.Resolve<IConfigurationService>();
public bool HasCompletedSecurity
{
get
{
// Uses the static _configurationService to get the
// configured value:
int numberOfRequiredResponses =
GetConfiguredNumberOfRequiredResponses();
return this.SecurityQuestionResponses.Count()
>=
GetConfiguredNumberOfRequiredResponses();
}
}
}
This is of course an example of the ServiceLocator anti-pattern, and I don't like it one bit. The static dependency makes unit testing anything which uses this class awkward.
I'm using the Entity Framework and taking a cue from here I don't want to pass my entities through a DI container to give them their dependencies, so... how should I be accessing the configured value instead?
Edit: With this exact example to one side (and I do appreciate the suggestions as to the correct architecture for it), the larger question I'm interested in is how do you manage non-static references to services from entities? Is the answer to just architect the entities in such a way that you never need to?
Here's how I would define the User class:
public class User
{
public bool HasCompletedSecurity { get; set; }
// other members...
}
Seriously, this is a better solution because it decouples the value along the temporal dimension. Consider this: if a user completed all security questions in 2010 and you later on change the business rule, are you then going to invalidate the existing user?
In most cases it would probably be more reasonable to record and persist that sometime in the past, the user completed the security procedure that was in effect at that time. In that way, you don't bother existing users.
You can still using the concept of Inversion of Control without using any sort IoC container or requiring its use in the constructor of your entity. I would approach this using a quasi-strategy pattern and have something like:
public interface ISecurityPolicy
{
public int MinimumSecurityQuestionResponses { get; }
}
public class User
{
public void HasCompletedSecurity (ISecurityPolicy security_policy)
{
return this.SecurityQuestionResponses.Count()
>= security_policy.MinimumSecurityQuestionResponses;
}
}
This puts the onus of providing the particular security policy that the user must satisfy on the caller, not the User class itself.
From that point on, you can provide that extra parameter however you want to, maybe be wrapping this in a IUserSecurityService that will have the ISecurityPolicy injected into the service, etc.
This is still Inversion of Control, but it's at the method level, since this one particular method is really the only one that cares about the security policy/configuration.
After much kicking and screaming, I'm starting to accept DI despite how much cleaner SL may seem as dependencies grow.
However, IMO there's still a significant show-stopper with regards to DI:
DI is not possible when you don't have control over an object's instantiation. In the ASP.NET world, examples include: HttpModule, HttpHandler, Page, etc.
In the above scenario we would resort to static service location to resolve dependencies, typically via HttpContext.Current, which invariably infers scope from the current thread. So if we're going to use static SL here, then why not use it else where too?
Is the answer as simple as: grit your teeth and use SL when necessary (like above), but try and favor DI? And if so: doesn't using static SL just once potentially break the consistency of an entire application? Essentially undoing the hard work of DI everywhere else?
Sometimes you just can't avoid tight coupling, like in your examples. However, that doesn't mean you need to embrace it either. Instead, quarantine it by encapsulating the messiness and factoring it away from your day-to-day life.
For example, if we want the current Forms Authentication user, we don't have much choice but to access HttpContext.Current.Request.User.Identity.Name. We do, however, have the choice of where to make that call.
HttpContext.Current is a solution to a problem. When we call it directly from where we use the results, we are declaring the problem and solution in the same place: "I need the current user name which is declared unwaveringly as coming from the current HTTP context." This muddles the definition of both and doesn't allow for different solutions to the same problem.
What we are missing is a clear articulation of the problem we are solving. For this example, it would be something like:
Determine the user which made the current request
The fact that we are using HttpContext.Current, or even a user name, is not a part of the core problem definition; it is an implementation detail that only serves to complicate the code requiring the current user.
We can represent the intent to retrieve the current user, sans implementation details, through an interface:
public interface IUserContext
{
User GetUser();
}
Any class where we called HttpContext.Current directly can now use this interface instead, injected by the container, to maintain DI goodness. It is also much more intention-revealing for a class to accept an IUserContext in its constructor than to have a dependency which can't be seen from its public API.
The implementation buries the static call in a single place where it can't harm our objects any more:
public class FormsUserContext : IUserContext
{
private readonly IUserRepository _userRepository;
public FormsUserContext(IUserRepository userRepository)
{
_userRepository = userRepository;
}
public User GetUser()
{
return _userRepository.GetByUserName(HttpContext.Current.Request.User.Identity.Name);
}
}
A good codebase is also one where the occasional restriction on the optimal solution is contained to a small area. The lack of possibility of DI partly explains the move from ASP.NET to the MVC counterpart. With HttpHandlers, I usually have a HttpHandler Factory which is the only class to get its "hands" dirty and instantiates HttpHandlers from a container.
Many DI containers have some kind of BuildUp method to perform setter injection on already instantiated objects. If you have service location, try to isolate it into some piece of your application that is purely an infrastructure concern. It will then act as a dampening field to the environment's limitations.
In short, some SL will not invalidate your efforts, but make sure the SL bits are infrastructural and well-contained.
To provide on #flq's answer with an example.
I'm working on an ASP.Net MVC project that makes rather extensive use of Ninject. There were a handful of places where I either couldn't use DI (Extension methods), or it was cleaner not to, and use SL instead (The base class for all of my controllers, constructor injection would make all the constructors for controllers messy).
So, as a compromise, I use a slight hybrid:
public interface IServiceLocator
{
T Create<T>();
}
public class NinjectServiceLocator : IServiceLocator
{
private readonly IKernel kernel;
public NinjectServiceLocator(IKernel kernel)
{
this.kernel = kernel;
}
public T Create<T>()
{
return kernel.Get<T>();
}
}
public class ServiceLocator
{
private static IServiceLocator current;
public static IServiceLocator Current
{
get
{
return current;
}
set
{
current = value;
}
}
public T Create<T>()
{
return current.Create<T>();
}
}
It may not be the best option, or a strict SL pattern, but it works for me. The additional interface lets me swap out the locator itself for testing. IKernel is Ninject's main DI object that gets configured, so substitute with your own framework, as most I've encountered have a similar core.
The typical approach in these cases is to write a generic infrastructure-level wrapper/adapter that does use Service Locator, but provides clean IoC for application-level classes that use this adapter.
I did this to enable IoC in HttpModules and Providers, two cases where the framework doesn't allow control of instantiation. A similar approach can be used for other similar entities.
The point here is that such wrapper/adapter code is part of your reusable infrastructure, and not your application-level code. What's generally not recommended is using service location in your application-level code.
The "BuildUp" feature that some containers offer are a poor workaround for these limitations. BuildUp doesn't allow you to regain control of instantiation, so you won't be able to use some container features such as proxying.
I'm trying to work out a way of passing the web current http context to a service class (or initialising the class with a reference to it). I am doing this to abstract the rest of the app away from needing to know anything about the http context.
I also want the service to be testable using TDD, probably using one of the Mockable frameworks. Hence it would be preferable to use an interface rather than an actual class.
An example of what I'd like to achieve:
class WebInstanceService
{
private IHttpContext _Context;
public WebInstanceService( ... , IHttpContext HttpContext )
{
....
_Context = HttpContext;
}
// Methods...
public string GetInstanceVariable(string VariableName)
{
return _Context.Current.Session[VariableName];
}
}
One of the main issues I have is that there is no IHttpContext, the .net http context is a subclass of an abstract class which can't be mocked (easily?).
Another issue is that I can't initialise global instances of the class as then the context won't be relevant for most requests.
I could make the class static, and require the Context to be passed to each function as it is called i.e.
public static string GetInstanceVariable(string VariableName, HttpContext Context)
{ ... }
but this doesn't make the class any easier to test, I still need to create an HttpContext and additionally any non-web-aware services which want to use this class suddenly need to be able to retrieve the Context requiring them to be closely coupled to the web server - the whole reason for wanting to create this class in the first place.
I'm open to ALL suggestions - particularly those which people know facilitate easy tdd testing. How would people suggest I tackle this problem?
Cheers
This is why HttpContextBase and HttpContextWrapper were introduced. You probably want to use HttpContextBase and when passing the real context in, use new HttpContextWrapper( httpContext ), although, I think that what is available to you in the controller is already of type HttpContextBase. I would create one of these in my controller each time rather than trying to reference the current context from the static, global HttpContext.Current instance. If you need it in your view, pass a reference to your strongly typed context in ViewData.
I mock up HttpContextBase frequently in my tests.
class WebInstanceService
{
private HttpContextBase _Context;
public WebInstanceService( ... , HttpContextBase HttpContext )
{
....
_Context = HttpContext;
}
// Methods...
public string GetInstanceVariable(string VariableName)
{
return _Context.Session[VariableName];
}
}
What we do is spin one of these up http://haacked.com/archive/2007/06/19/unit-tests-web-code-without-a-web-server-using-httpsimulator.aspx
Easy as pie, just instanciate an HttpSimulator and fill in the values, and HttpContext.Current gets filled up with whatever you specify.
IHttpContext is something that is in MVC, and aparently one day will be in webforms. Hopefully that day will be .net 4
ASP.NET comes with System.Web.Abstractions that include HttpContextBase that you can use for dealing with the HttpContext in a testing situation.
I would personally abstract away the direct dependency on the HttpContext.