Can Structuremap DefaultConventionScanner find non-public classes - structuremap

I have just started using StructureMap, having previously worked with Spring.Net. I love the DefaultConventionScanner and the ability to scan assemblies and use convention over configuration to find classes. But there seems to be a limitation that the classes that implement the interfaces must be public, whereas we like to keep out interfaces public and our implementations internal to an assembly.
Is there a way to ask the DefaultConventionScanner to find internal classes as well?

No, and in fact the limitation that classes should be public applies to all of StructureMap - not just the convention scanners. You can register internal types manually with StructureMap if you make use of the InternalsVisibleTo attribute, but it is not well-supported or documented. You will not be able to make an ITypeScanner (like DefaultConventionScanner) that registers internal types because the AssemblyScanner only exposes exported types.

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.

Dependency injection modular dependency registration

I try to design my applications always in a modular fashion. I want to be able at any given to swap modules.
Using the dependency injection pattern allows me to do just that. But there is something that keeps bothering me a lot.
In most of the code I come across there is a single place where interfaces are linked to the desired interface. For example in asp.net vnext it looks something like this:
public void ConfigureServices(IServiceCollection services)
{
// business-layer
services.AddTransient<IArticleRepository, ArticleRepository>();
// data-layer
services.AddTransient<IDataConnection, DataConnection>();
}
But I don't like that there is only one place to do the registration. I would rather have each module register their own interfaces/implementations:
In my business layer (module)
public void ConfigureServices(IServiceCollection services)
{
// business-layer
services.AddTransient<IArticleRepository, ArticleRepository>();
}
In my data layer (module)
public void ConfigureServices(IServiceCollection services)
{
// data-layer
services.AddTransient<IDataConnection, DataConnection>();
}
Is there any pattern, or best-practice to do this kind of things? I could create some interface and on load go through all the implementations of this interface, but I'm not sure if this is the best way to do this.
Is there any pattern, or best-practice to do this kind of things?
Yes and no. There's the Facade pattern where you provide a simplified API to clients that don't need fine-grained control of your API. The Facade pattern doesn't explicitly concern itself with Dependency Injection, but you can always provide a default composition of services if that's a meaningful thing to do. There are more details in my article DI Friendly Library.
That said, it's important to keep the API open, so that the Facade is only one of the options you provide to clients. If you pre-compose an object graph within a library, and don't provide clients any way to circumvent that default composition, such a library would be a monolithic black box. All external benefits from Dependency Injection would be gone, because a client wouldn't be able to replace or extend services.
Do follow the guidelines outlined in the DI Friendly Library article, but be sure to avoid the Conforming Container anti-pattern.
i would say that way/place of configuring your DI depends highly on your DI framework. some frameworks let you do per-module configuration others require one global configuration. in the latter case you can manually delegate to your submodules (just pass the IServiceCollection to submodule configuration code).
regarding best practices: i rarely see usage of DI to have multiple production implementations. usually there is just one production implementation and DI is used just to wire together everything without the boilerplate. but many different implementations (usually mocks) are used in testing usually with manual wiring without the DI framework. if that's also your case then your gut-felling is right: it would be nice to have DI framework that scan the whole code, take the default/only implementation and inject it as a dependency. if your DI framework provides that functionality you're lucky. if not, you have to implement it by yourself

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.

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.

StrcutureMap Wiring - Sanity Check Please

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

Resources