StructureMap passing null in constructor

I am having difficulty using StructureMap for services, where the constructor has an argument with a null value. I.e

 public JustGivingService(IRestClient restClient = null) 

In my configuration with all the other services, I am usually able to get away with the minimum, so the problem here is probably just a lack of understanding. I would do this:

 container.For<IJustGivingService>().Use<JustGivingService>() 

However, due to the nullable parameter, I will find that I will need to use this instead to make it work:

 RestClient restClient = null; container.For<IJustGivingService>().Use<JustGivingService>() .Ctor<IRestClient>("restClient").Is(restClient); 

However, for me this is a bit dirty, and I feel that this is probably a workaround for what I'm trying to achieve, and not a standard way to do it. If there is a better way to do this, the accompanying information on why this will be very helpful.

+5
source share
1 answer

StructureMap does not support optional constructor parameters, and it should not. As described in this blog post :

An optional dependency implies that the reference to the dependency will be null if it is not specified. Null references complicate the code because they require specific logic for the null case. Instead of passing a null reference, the caller can insert an implementation without any behavior, that is, an implementation of a null object template. This ensures that dependencies are always available, the type may require these dependencies, and there are no scary checks. This means that we have less code for maintenance and testing.

So, the solution is to create a Null Object for IRestClient and register this implementation in StructureMap.

Example:

 // Null Object pattern public sealed class EmptyRestClient : IRestClient { // Implement IRestClient methods to do nothing. } // Register in StructureMap container.For<IRestClient>().Use(new EmptyRestClient()); 
+5
source

Source: https://habr.com/ru/post/1246864/


All Articles