Refactoring large application for ObjectFactory.GetInstance to use nested containers - structuremap

I have a large application which uses the old way of getting instances using ObjectFactory.GetInstance().
Now I want to move to application to the more correct way of injecting dependencies using constructor injection. However, it is almost impossible to convert all code at once (some static classes use ObjectFactory.GetInstance, other services do not have constructors with all dependencies, ...).
I was wondering if there is a way of replacing ObjectFactory.GetInstance calls with an replacement that uses the current nested container, e.g. replacing all ObjectFactory.GetInstance with Ioc.GetCurrentNestedContainer().GetInstance, to get it quickly up an running.
But how would I could I implement Ioc.GetCurrentNestedContainer to return the currently active nested container?
I can not inject IContainer in all these classes (some are static or have no corresponding
constructor), so they can not use constructor injection (yet).
DI is used in MVC, WCF, and Task based scenarios in this application.

Whilst I can't talk about WCF and task based scenarios, I can offer my recommendation for MVC (having spent time looking the options to a similar problem myself.
The solution to I've come across and ultimately settled for after seeing recommendations by StructureMap's creator, is to have a HttpContext bound nested container created on each request and stored within HttpContext.Items. From here you can reference the container by casting the instance stored within HttpContext.Items to an IContainer.
Infact, this is the same solution used within the StructureMap.MVC5 nuget package.
With this solution in mind, there's nothing to stop you replacing the ObjectFactory with with your own factory that returns the nested container from HttpContext.Items.
Update:
If HttpContext isn't available to you then the only other options I'm aware of is to create your own instance of the object factory that creates a new container and stores it in a Lazy<T> as suggested here and on the StructureMap's Google Groups page here.
I was going to suggest possiblity posting this question on the StructureMap Google Groups, but I see you've already done that. As an avid StructureMap user I'm keen to see what other suggestions arise from your post so I will be watching closely.

Related

Dependency injection - trying to avoid using a service locator

Following the guidelines I read in:
https://www.devtrends.co.uk/blog/how-not-to-do-dependency-injection-the-static-or-singleton-container
I want to try and avoid using a service locator.
But on the other hand, I don't register all the types in the startup.cs file. I don't think this is right that all these internal types are referenced in the main startup.cs
I currently have a factory class that has a collection of builder classes.
Each builder class is in charge of creating a specific object.
I don't want to create all these builder classes in advance as I might not need to use them and creating them is a bit heavy.
I saw an example of how to achieve this in the link above. However the startup.cs class needs to know all these builders. I don't think this is appropriate, I'd rather have the factory class be the only one that is exposed to them. I was trying to understand if there is some kind of func/action method that I can inject from the startup.cs file into my factory class. This func/action will be in charge of creating/registering the builders and then I can activate this func/action within the class factory. I'd like this func/action to receive the interface/class/maybe name of the builder but using generics isn't working. I searched a lot and didn't find any solution so I assume this is not possible.
Seems I have 2 options:
1. Use service locator. This way only the factory class will know the builders. However if in the future, if I want to change the DI I need to "touch" the factory class (I'm contaminating the factory class). Wanted all the DI code to be located only in the startup.cs class.
2. Register the builders in the startup.cs but now the startup.cs is aware of the builders. This kinda couples the code, not really single role of responsibility
It would have been great to inject the factory class a func/action from the startup.cs that would do the registration but the factory class itself activates it.
Is this possible?
I want to try and avoid using a service locator
Great, because the Service Locator is an anti-patttern.
don't register all the types in the startup.cs file.
You should do your registrations in one single 'area' of your application: the start-up path. This area is commonly referred to as the Composition Root (the place where object graphs are composed).
I don't think this is right that all these internal types are referenced in the main startup.cs
No matter how you design it, the startup assembly is the most volatile part of the system and it always depends on all other assemblies in the application. Either directly or transitively (through another referenced assembly). The whole idea of Dependency Injection is to minimize the coupling between components and the way to do this is to centralize coupling by moving it to the Composition Root. By making types internal however, you are decentralizing object composition and that limits your flexability. For instance, it becomes harder to apply decorators or interceptors for those registered types and control them globally. Read this question and its two top voted answers for more information.
I don't register all the types
The concern of having a Composition Root that is too big is not a valid one. One could easily split out the Composition Root into multiple smaller functions or classes that all reside in the startup assembly. On top of that, if you read this, you'll understand that registering all types explicitly (a.k.a. "Explicit Register") is typically pointless. In that case you're probably better off in using DI without a Container (a.k.a. Pure DI). Composition Roots where all types are registered explicitly are not very maintainable. One of the areas a DI Container becomes powerful is through its batch-registration facilities. They use reflection to load and register a complete set of types in a few lines of code. The addition of new types won't cause your Composition Root to change giving you the highest amount of maintainability.
I don't want to create all these builder classes in advance as I might not need to use them and creating them is a bit heavy
Creation of instances should never be heavy. Your injection constructors should be simple and composing object graphs should be reliable. This makes building even the biggest object graphs extremely fast. Factories should be reduced to an absolute minimum.
TLDR;
Register or compose your object graphs solely in the Composition Root.
Refrain from using the Service Locator anti-pattern; Whole applications can (and should) be built purely with Constructor Injection.
Make injection constructors simple and prevent them from doing anything else than storing their incoming dependencies.
Refrain from using factories to compose services, they are not needed in most cases.

Multitenancy, help understand concept of WorkContext

While trying to understand how a multitenant environment works, I've came up to the concept of WorkContext.
Introduction:
In a multitenant environment Tenants are Clients which share similar functionality, and run under a single instance of a ROOT application. In order to be able to add tenant specific functionality I came across a conclusion that Dependency Injection is the right solution for my case.
Each tenant should have it's own IoC Container, in order to be able to Resolve its dependencies at runtime.
But when trying to implement the theory I have some troubles with the wrapping out all tenant specific data.
While digging the internet it seems that there must exist some sort of a TenantContext. So each tenant has it's own isolated Context.
The problem is that I don't understand the true LifeCycle of such a Context.
Question 1:
What is the lifecycle diagram of a tenant specific WorkContext, Where should I store it, When it should be created/disposed ?
NOTE: If the question 1 is provided, there is no need to answer the above one.
Suddenly I've found Orchard Project which seems to be a true masterpiece. Inside Orchard, the Context i'm talking about is called WorkContext.
I'm trying to understand the concept of WorkContext in Orchard Project. As far as I understand, here are some thoughts about WorkContext:
The WorkContext is a per-request lifetimeobject.
It is stored in HttpContext.Items (also there is a thread static implementation..).
It wraps the tenant IoC scope (ShellContext -> ShellContainer).
It is accessed through IWorkContextAccessor.
What I don't understand is:
Question 2:
Why do we need to include IWorkContextAccessor instance in route's DataTokens like this: routeData.DataTokens["IWorkContextAccessor"] = _workContextAccessor; ? Is this really necessary?
Kind of big question :-).
Firstly, WorkContext is more or less an abstraction of the HTTP context. A WorkContext lives as long as its work context scope lives (see IWorkContextAccessor that you can use to create work context scopes) so actually you can have multiple work contexts per request and you can have a work context independently of a request too (this happens in background tasks).
Such work contexts are thus externally managed contexts and thus somehow have to "travel" along with their scope until the latter is terminated: in Orchard the WC is either carried in the HTTP Context or in a thread static field (what is not good enough and should be changed).
Thus basically a work context scope is the lowest dependency scope commonly used. It also has a parent, the shell's scope: this is the shell context (or more precisely, its lifetime scope). You can access a shell's (what is most of the time equal to a tenant) context through IOrchardHost.GetShellContext(). Work context scopes are actually created from the shell context's lifetime scope.
This also has a parent BTW that is the application-wide HostContainer.
Most of the time you don't have to manage the WC yourself since the ambient WC around requests and background tasks are managed for you.
Regarding your second question: I'm not entirely sure about this but AFAIK passing the WCA to the routeData just serves as a workaround to be able to access it (and thus, Orchard services) from strange places like HTML helpers and attributes that are not resolved through the DI container.
Edit: also added this to the Dojo Library, redacted and improved: http://orcharddojo.net/orchard-resources/Library/Wiki/WorkContext

Replacement for Dependency Injection Container in Rails

I have read dozens of articles about this and still have some questions.
How are services used in multiple parts of the system? For example, I have a permissions component that is used by several other classes during a request. Right now, I have made it a singleton. I have been using singletons as the entry point to portions of my domain (various services) that need to be reused during a request. This seems to be the only way I can access these services in different parts of the system without reinstantiating them or without throwing them in a global variable. In other systems, I would make it a normal class and set it's lifecycle to "request". The container would make sure that it is shared within the request and release it for garbage collection.
I have thought about using a service locator which stores services in Thread.current. But this feels like I'm getting desperate.
The main way I've seen that people accessing these dependencies is to wrap the dependency in a method:
class A
def some_dep
SomeService.instance
end
end
In tests, some_dep is overridden to return a mock or whatever. This seems like the best so far but still feels hackish.
My options for using services within a request seem to be:
1) Put them in a global variable / Thread.current.
2) Use a service locater.
3) Pass dependencies around manually (complete disaster).
4) Singleton.
Two questions:
1) What is the best approach for making services available to multiple parts of the system without reinstantiating?
2) What is the best approach for a class to manage those dependencies?
Note:
I understand that I can put reusable functionality into modules. IMO, however, modules are great for purposes of staying DRY but not for carrying state around the system (i.e. which tenant you're on in a multitenant application).

Autofac Container Independence and Relationship Types

We are currently using Autofac as our chosen IoC container. All application code in our reusable assemblies must be kept as clean as possible, so we do not want any direct dependencies on Autofac in our core application. The only place where Autofac is permitted is in the composition root / bootstrappers, where components are registered and wired up. Applications rely on dependency injection to create the required object graphs.
As we are keeping our core application container agnostic, it means that we cannot use the Autofac relationship types, such as Owned, in our core application.
I would like to create a factory that returns components that implement IDisposable. As Autofac tracks disposable objects, I believe I have to use a lifetime scope to create a defined unit of work in which components will be disposed once they go out of scope.
According to the Autofac documentation, this can be achieved by taking a dependency on Func<Owned<T>>, however, as stated above, I cannot take a dependency on Owned as it is an Autofac type. At the bottom of this page, it says
The custom relationship types in Autofac don’t force you to bind your application more tightly to Autofac. They give you a programming model for container configuration that is consistent with the way you write other components (vs. having to know a lot of specific container extension points and APIs that also potentially centralise your configuration.)
For example, you can still create a custom ITaskFactory in your core model, but provide an AutofacTaskFactory implementation based on Func<Owned<T>> if that is desirable.
It is this implementation of ITaskFactory that I believe I need to implement, but I cannot find any examples.
I would be very grateful if someone could provide such an example.
Probably the best "real-world" example of this is the Autofac MVC integration mechanism. While it doesn't use Func<Owned<T>> under the covers it does show you how you might be able to implement a non-Autofac-specific mechanism to talk to Autofac under the covers.
In the MVC case, the System.Web.Mvc.IDependencyResolver is the interface and the Autofac.Integration.Mvc.AutofacDependencyResolver is the implementation. When ASP.NET MVC requests a service, it gets it from System.Web.Mvc.DependencyResolver.Current, which returns an IDependencyResolver. At app startup, that singleton gets set to the Autofac implementation.
The same principle could hold for your custom factory. While IDependencyResolver is not specific to the type it returns (it's just GetService<T>()) you could write a type-specific factory interface just as easily.

Should service layer have access to HttpContext?

I'm building an application that roughly follows the repository pattern with a service layer on top, similar to early versions of Conery's MVC Storefront.
I need to implement a page that returns all users except for the current user. I already have GetUsers() methods on the repository and service layers, so the question is where to apply the "except for the current user."
Should the service layer be aware of HttpContext, thus applying this rule? I am tempted to just pass in the current user (id) from the controller to this service method, but it seems cleaner if the service layer was HttpContext-aware and could do this on its own.
One obvious alternative is to apply this rule directly within the Controller, but I'm just not hot on that idea...
Edit - just to comment on the answers: I see the issues with the reverse dependency problem, something I was completely overlooking. I'm marking Mehrdad's as the answer due votes, but everyone has really provided a valuable response worth reading!
Absolutely not. My mindset in designing these kind of things is like this: I assume I need to write a Windows based app along with the Web application and try to minimize dependency on Web specific stuff. Passing HttpContext directly will increase coupling of your service layer to your Web UI layer which is not ideal.
The answer is, no.
Not only should the Service Layer have no dependency on the current Presentation Layer, in my opinion it should have no dependency on the current application. For instance, I would not use a custom AppContext class as JonoW suggested here.
Instead, pass the current user as a parameter to the GetAllUsersExceptForTheCurrentUser method.That way, the service can be used by any application that needs to process users, not only the current application.
You should not create a reverse dependency between your service layer and the web tier. Consider what happens when you want to extend your service layer to work with a forms-based application or windows service. Now you've got to work around the web dependency to get your same methods to work or duplicate some (perhaps, small, but still duplicate) code. You would be better served to extract the user's identifier into something useful in the context of the service layer and use that value with the service layer. Handling the filtering on the web site is also acceptable, though if you do it more than once it would need to be refactored into a common place and the service layer is the natural spot for it.
I find it good practice to build a custom AppContext class which contains my current user object (as well as other contextual data). This class has no references to System.Web. Any service methods that need to be context aware should have an AppContext parameter (e.g. for checking security rights, or getting the current user as in your case). Populate this object in the web-tier and keep it in session if you need to. This way your service layer knows nothing about System.Web.
No. Doing so will make your code harder to test and re-use.
I tend to build an infrastructure interface for this sort of thing (call it IAuthentication or something) and expose a CurrentUser property on it. Then I'd inject this into my service via its a constructor. i.e. public MyService(IAuthentication auth)
Finally you'd can build an HttpContext aware implementation of IAuthentication (say WebAuthentication).
Now when you create your service you create its dependencies as well:
var myService = new MyService(new WebAuthentication());
var otherUsers = myService.GetAllOtherUsers();
If you are using an IoC container the ugly dependency can even go away!

Resources