StrcutureMap Wiring - Sanity Check Please - dependency-injection

Im new to IOC and StructureMap and have an n-level application and am looking at how to setup the wirings (ForRequestedType ...) and just want to check with people with more experience that this is the best way of doing it!
I dont want my UI application object to reference my persistence layer directly so am not able to wire everything up in this UI project.
I now have it working by defining a Registry class in each project which wires up the types in the project as needed. The layer above registers its types and also calls the assembly below and looks for registries so that all types are registered throught the hierrachy.
E.g. I have UI, Service, Domain, and Persistence libraries. In my service layer the registry looks like
Scan(x =>
{
x.Assembly("MyPersistenceProject");
x.LookForRegistries();
});
ForRequestedType<IService>().TheDefault.Is.OfConcreteType<MyService>();
Is this a recommended way of doing this in a setup such as this? Are there better ways and what are the advantages / disadvantages of these approaches in this case?

This sounds good.
If you use default conventions, like having a default implementation OrderSevice for the interface IOrderService you can reduce the wiring by using conventions in StructureMap. The WithDefaultConventions is a method in the Registry to use default conventions. You can also specify your own convention and register it in the registry using the method With, see the StructureMap documentation

Related

Named bulk registration with windsor castle

In my project I have the interface IProcess and a lot of classes implementing this interface. I need to register all those implementations. The following code is working fine for me:
Container.Register(Component.For<IProcess>().Named("SampleProcess").ImplementedBy<SampleProcess>());
Container.Register(Component.For<IProcess>().Named("SampleProcess2").ImplementedBy<SampleProcess2>());
However using this approach for registering is tedious if I have a lot of implementations. Therefore I am looking for a registration method to register all implementations of IProcess in a given assembly by name. The name that should be used for the registration key is just the class name.
Can someone pls give me a hint where to look for?
Sounds like a classic scenario for the convention registration API.
container.Register(
Classes.FromThisAssembly()
.BasedOn<IProcess>()
.WithServiceBase()
// and then if you *really* need to explicitly control naming
.Configure(c => c.Named(c.Implementation.Name)
)
Generally explicitly naming your components shouldn't be used, unless you have multiple components with the same implementation class, so just make sure you really need it.

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.

Dependency Injection - Passing dependencies all the way down

I have an MVC application with a typical architecture...
ASP.NET MVC Controller -> Person Service -> Person Repository -> Entity Framework DB Context
I am using Castle Windsor and I can see the benefit of using this along with a ControllerFactory to create controller with the right dependencies. Using this approach the Controller gets a Service injected, which in turn knows how to construct the right Repository, which in turn knows the correct DbContext to use.
The windsor config is something like this...
dicontainer = new WindsorContainer();
dicontainer.Register(Component.For<IPersonService>().ImplementedBy<PersonService>());
dicontainer.Register(
Component.For<IPersonRepository>().UsingFactoryMethod(
() => new PersonRepository(new HrContext("connectionString"))));
It this the right way to do it? I don't like the UsingFactoryMethod, but can't think of another way.
Also, what if the Repository needed a dependency (say ILogger) that was not needed by the service layer? Does this mean I have to pass the ILogger into the service layer and not use it. This seems like a poor design. I'd appreciate some pointers here. I have read loads of articles, but not found a concrete example to verify whether I am doing this right. Thanks.
I try to avoid using factory methods (as you mentioned you felt this smelled funny). To avoid this, you could create a database session object that creates a new DbContext. Then your repositories just need to get an instance of IDbSession and use its dbContext property. Then, you can also easily control the scope of the IDbSession object (don't use singleton because it's not thread safe).
I wanted to make that point so that I could make this more important point... Make your constructors take in only objects that are registered in the DI container (no options or configurations in constructors). Options and configurations should be read/writen in classes whose sole purposes it is to read/write those values. If all classes follow this model, then your DI registration becomes easy and classes can just add whatever dependencies they need in their constructors.
If you are trying to use a third party library that has options in constructors, wrap that class in your own class that has an easy to consume constructor and uses a configuration class to read the values needed to pass to the third party library. This design also introduces a layer of abstraction between your code and the third party library which can then be used to more easily swap (or stub) third party libraries when necessary.

What is Caliburn Validation abstraction

Recently I saw this document that specify how great is Caliburn(Not really it compares it to the micro framework, and thats enough).
I'm working with Caliburn for more than a year and don't know many things about it.
So maybe someone can explain the following(Some of it I can understand but have no iea about the relation to caliburn):
Validation abstraction
module framework
ExpressionTree-Based runtime delegate generation
ViewModelFactory
ShellFramework
I'm working with V1.1 so if something is new in 2.0, just say it belong to the new version I'll learn it probably in the future.
The validation abstraction is aimed to plug a validation infrastructure in ViewModels.
Caliburn's DefaultValidator uses System.ComponentModel.DataAnnotations, but an adapter for Fluent Validation is also available.
While the validation could be used directly from application code, it is used by the framework mainly in the AOP validation behavior, which provides an automatic IDataErrorInfo implementation for models.
If your models already implement IDataErrorInfo, Caliburn is able to hook the validation (as a part of conventional binding process) leveraging plain WPF binding.
Yet, implementing IDataErrorInfo manually is boring and likely to lead to hardly mantainable code, so the AOP [ValidateAttribute] was introduced.
To enable it, you have to configure your container to use the available proxy factory (which is based upon Castle.DynamicProxy):
myContainerAdapter
.WithProxyFactory<Caliburn.DynamicProxy.DynamicProxyFactory>()
This instructs the container adapter to inspect behaviors attribute applied on the ViewModels (and other components) pulled from the container, and to create a subclass of them implementing the specified behavior.
The [Validate] behavior implementation just delegates 'IDataErrorInfo' calls to the actual IValidator service.
Module framework is used by Caliburn itself to manage configuration and initialization of its own modules. It could also be used to create independent application modules: Caliburn will take care of discovering them (if their assemblies are registered in IAssemblySource) an drive their initialization;
Caliburn doesn't use reflection to invoke action, but builds delegates on the fly leveraging Expression Trees to create a compiled lambda;
The ViewModelFactory service is used by Caliburn to abstract the creation of VM, either by type or by Subject handled;
ShellFramework contains a set of facility useful to build most applications; it includes some custom IResult (along with fluent-style static methods to create them) and some pre-built ViewModels (Menus and Question/Message dialog) to accomplish common application tasks.

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