Strategy for using command line args with Unity DI? - c#

I'm using the Unity framework to inject a ConfigurationProvider into some of my classes via the following interface:
interface IConfigurationProvider<T>{
T GetConfiguration();
}
then, in my bootstrapper with Unity,
container.RegisterType(typeof (IConfigurationProvider<DongleConfiguration>),
typeof (DongleConfigurationProvider));
This has been a good strategy up until now & has allowed me to define different config providers for various implementations & tests. Now, I'd like one of the providers to use command line arguments to set up a config object, which requires me to pass along the args parameter to the ctor:
class ProblematicConfigurationProvider : IConfigurationProvider<ProblematicConfiguration> {
...
public ProblematicConfigurationProvider(string[] args) { ... }
...
}
I've read that I can use ParameterOverride to supply an optional ctor argument as such:
var configObj = container.Resolve<IConfigurationProvider<ProblematicConfiguration>>(new ParameterOverride("args", args));
However, I'm using DI "all the way" and relying on the container to resolve dependencies down the line after resolving RootObject or whatever my top level class is. My question is, how can I now use the configObj object I've just resolved if it's buried somewhere down deep in my dependency graph? How can I use a resolved object in another call to Resolve? Would it be through a similar use of ParameterOverride? Is there a way to set up the param override somewhere & have Unity use it without actually instantiating configObj?

I would do this differently. Add a CommandLineArguments class to your project, which just wraps the command line arguments. As part of your container initialization, register that with the container:
container.RegisterInstance(new CommandLineArguments(args));
Then your ConfigurationProvider should have a dependency of CommandLineArguments, not string[]. From there, it should just resolve everything naturally "all the way down" without using the parameter overrides.
Since your command line arguments aren't going to change, this makes it a lot simpler in my opinion.
Note: I use the CommandLineArguments type because it's a lot more descriptive of what's going on. You could register the string[] directly into the container, but that would feel a little wierd to me, and possibly inject you command line arguments somewhere you don't expect.

Related

ASP.NET Core option dependency in constructor

I'm using ASP.NET Core and I'm attempting to create a resolvable class which has an optional parameter:
public class Foo
{
public Foo() : this(null)
{}
public Foo(IValidator<FooEntity> validator)
{
}
}
I've created two constructors for this object so that if a dependency isn't found, I would assume it would just fall back to the default constructor.
However when I run my application I receive this error
Additional information: Unable to resolve service for type 'FluentValidation.IValidator`1[FooEntity]' while attempting to activate 'Foo'
I know there is probably a way to manually resolve the construction of the Foo object. But I would prefer not to do that because I will have to do this for every class that I create without a validator.
Does anyone know how to configure ASP.NET Core DI to fall back to a different constructor if the dependency is not found?
EDIT
Sorry, I should of been a bit more clear before.
This Foo class I'm referring to in really a base class for a CRUD Service, which will be used over and over again.
I'm looking for a generic solution which doesn't require me to configure each Service I create each time.
So using a lambda to resolve this is not an option, The null object pattern seems feasible but I can't comprehend how to write a generic one in which I won't have to configure for each service
I think its general behavior of Containers to resolve the constructor with the most parameters.
Basically what AddTransient does is the following:
services.AddTransient<Foo>();
//equals to:
services.AddTransient<Foo>(c=> new Foo(c.GetService<IValidator<FooEntity>()));
So you can register it yourself like this:
services.AddTransient<Foo>(c=> new Foo());
At this point in the startup class you should know if IValidator<FooEntity> has been registered. Or, if you are using reflection add this logic to your reflection code.
Difference
The difference between the 2 options is that with the first option is that the lambda function to resolve the class is created on startup. + if you change the constructor no code needs to be changed elsewhere.
If you create the lambda yourself this lambda is compiled on build, so theoretically startup should be faster (I have not tested this).
Great mindset
A great mindset is to own the libraries you are using. In Visual studio/Resharper you can decompile source-code, or you can find the repositories on github nowadays.
There you can see the source code, you can see how the services parameters is 'compiled' to the IServiceProvider (see BuildServiceProvider() method, it will give you alot of insight.)
Also look at:
ServiceDescriptor, Your type registration.
Service, the one that resolves the type.
Solution
best way to do it is this, (sorry for psuedo code but i have no editor at hand).
getTypes()
.Where(x=> x.EndsWith("Entity") //lets get some types by logic
.Select(x=> typeof(IValidator<>).MakeGeneric(x)) //turn IValidator into IValidator<T>
.Where(x=> !services.IsRegistered(x))
.Each(x=> services.Add(x, c=> null)) //register value null for IValidator<T>
You need to register the IValidator<T> first:
var services = new Microsoft.Extensions.DependencyInjection.ServiceCollection();
services.AddTransient<IValidator<FooEntity>, RealValidator<FooEntity>>();
services.AddTransient<Foo>();
var serviceProvider = services.BuildServiceProvider();
var validator = serviceProvider.GetService<IValidator<FooEntity>>();
var foo = serviceProvider.GetService<Foo>();
Assert.NotNull(validator);
Assert.NotNull(foo);

Dependency Injection composition root and decorator pattern

I'm getting StackoverflowException's in my implementation of the decorator pattern when using dependency injection. I think it is because I'm "missing" something from my understanding of DI/IoC.
For example, I currently have CustomerService and CustomerServiceLoggingDecorator. Both classes implement ICustomerService, and all the decorator class does is use an injected ICustomerService but adds some simple NLog logging so that I can use logging without affecting the code in CustomerService while also not breaking the single responsibility principle.
However the problem here is that because CustomerServiceLoggingDecorator implements ICustomerService, and it also needs an implementation of ICustomerService injected into it to work, Unity will keep trying to resolve it back to itself which causes an infinite loop until it overflows the stack.
These are my services:
public interface ICustomerService
{
IEnumerable<Customer> GetAllCustomers();
}
public class CustomerService : ICustomerService
{
private readonly IGenericRepository<Customer> _customerRepository;
public CustomerService(IGenericRepository<Customer> customerRepository)
{
if (customerRepository == null)
{
throw new ArgumentNullException(nameof(customerRepository));
}
_customerRepository = customerRepository;
}
public IEnumerable<Customer> GetAllCustomers()
{
return _customerRepository.SelectAll();
}
}
public class CustomerServiceLoggingDecorator : ICustomerService
{
private readonly ICustomerService _customerService;
private readonly ILogger _log = LogManager.GetCurrentClassLogger();
public CustomerServiceLoggingDecorator(ICustomerService customerService)
{
_customerService = customerService;
}
public IEnumerable<Customer> GetAllCustomers()
{
var stopwatch = Stopwatch.StartNew();
var result = _customerService.GetAllCustomers();
stopwatch.Stop();
_log.Trace("Querying for all customers took: {0}ms", stopwatch.Elapsed.TotalMilliseconds);
return result;
}
}
I currently have the registrations setup like this (This stub method was created by Unity.Mvc):
public static void RegisterTypes(IUnityContainer container)
{
// NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements.
// container.LoadConfiguration();
// TODO: Register your types here
// container.RegisterType<IProductRepository, ProductRepository>();
// Register the database context
container.RegisterType<DbContext, CustomerDbContext>();
// Register the repositories
container.RegisterType<IGenericRepository<Customer>, GenericRepository<Customer>>();
// Register the services
// Register logging decorators
// This way "works"*
container.RegisterType<ICustomerService, CustomerServiceLoggingDecorator>(
new InjectionConstructor(
new CustomerService(
new GenericRepository<Customer>(
new CustomerDbContext()))));
// This way seems more natural for DI but overflows the stack
container.RegisterType<ICustomerService, CustomerServiceLoggingDecorator>();
}
So now I'm not sure of the "proper" way of actually creating a decorator with dependency injection. I based my decorator on Mark Seemann's answer here. In his example, he is newing up several objects that get passed into the class. This is how my it "works"* snippet works. However, I think I have missed a fundamental step.
Why manually create new objects like this? Doesn't this negate the point of having the container doing the resolving for me? Or should I instead do contain.Resolve() (service locator) within this one method, to get all the dependencies injected still?
I'm slightly familiar with the "composition root" concept, which is where you are supposed to wire up these dependencies in one and only one place that then cascades down to the lower levels of the application. So is the Unity.Mvc generated RegisterTypes() the composition root of an ASP.NET MVC application? If so is it actually correct to be directly newing up objects here?
I was under the impression that generally with Unity you need to create the composition root yourself, however, Unity.Mvc is an exception to this in that it creates it's own composition root because it seems to be able to inject dependencies into controllers that have an interface such as ICustomerService in the constructor without me writing code to make it do that.
Question: I believe I'm missing a key piece of information, which is leading me to StackoverflowExceptions due to circular dependencies. How do I correctly implement my decorator class while still following dependency injection/inversion of control principles and conventions?
Second question: What about if I decided I only wanted to apply the logging decorator in certain circumstances? So if I had MyController1 that I wished to have a CustomerServiceLoggingDecorator dependency, but MyController2 only needs a normal CustomerService, how do I create two separate registrations? Because if I do:
container.RegisterType<ICustomerService, CustomerServiceLoggingDecorator>();
container.RegisterType<ICustomerService, CustomerService>();
Then one will be overwritten meaning that both controllers will either both have a decorator injected or a normal service injected. How do I allow for both?
Edit: This is not a duplicate question because I am having problems with circular dependencies and a lack of understanding of the correct DI approach for this. My question applies to a whole concept not just the decorator pattern like the linked question.
Preamble
Whenever you are having trouble with a DI Container (Unity or otherwise), ask yourself this: is using a DI Container worth the effort?
In most cases, the answer ought to be no. Use Pure DI instead. All your answers are trivial to answer with Pure DI.
Unity
If you must use Unity, perhaps the following will be of help. I haven't used Unity since 2011, so things may have changed since then, but looking up the issue in section 14.3.3 in my book, something like this might do the trick:
container.RegisterType<ICustomerService, CustomerService>("custSvc");
container.RegisterType<ICustomerService, CustomerServiceLoggingDecorator>(
new InjectionConstructor(
new ResolvedParameter<ICustomerService>("custSvc")));
Alternatively, you may also be able to do this:
container.RegisterType<ICustomerService, CustomerServiceLoggingDecorator>(
new InjectionConstructor(
new ResolvedParameter<CustomerService>()));
This alternative is easier to maintain because it does not rely on named services, but has the (potential) disadvantage that you can't resolve CustomerService through the ICustomerService interface. You probably shouldn't be doing that anyway, so it ought not to be an issue, so this is probably a better alternative.
Question: I believe I'm missing a key piece of information, which is leading me to StackoverflowExceptions due to circular dependencies. How do I correctly implement my decorator class while still following dependency injection/inversion of control principles and conventions?
As was already pointed out the best way to do this is with the following construct.
container.RegisterType<ICustomerService, CustomerServiceLoggingDecorator>(
new InjectionConstructor(new ResolvedParameter<CustomerService>()));
This allows you to specify how the parameters are resolved by type. You could also do it by name but by type is a cleaner implementation and allows for better checking during compile time as a change or mistype in a string will not be caught. Note that the only minute difference between this code part and the code offered by Mark Seemann is a correction in the spelling of InjectionConstructor. I will not elaborate on this part any more as there is nothing else to add that Mark Seemann has not already explained.
Second question: What about if I decided I only wanted to apply the logging decorator in certain circumstances? So if I had MyController1 that I wished to have a CustomerServiceLoggingDecorator dependency, but MyController2 only needs a normal CustomerService, how do I create two separate registrations?
You can do this using the way specified above using the Fluent notation OR using named dependency with a dependency override.
Fluent
This registers the controller with the container and specifies an overrload for that type in the constructor. I prefer this approach over the second but it just depends on where you want to specify the type.
container.RegisterType<MyController2>(
new InjectionConstructor(new ResolvedParameter<CustomerService>()));
Named dependency
You do this the exact same way, you register both of them like so.
container.RegisterType<ICustomerService, CustomerService>("plainService");
container.RegisterType<ICustomerService, CustomerServiceLoggingDecorator>(
new InjectionConstructor(new ResolvedParameter<CustomerService>()));
The difference here is that you use a named dependency instead for the other types that can be resolved using the same interface. This is because the interface needs to be resolved to exactly one concrete type every time a resolve is done by Unity so you can not have multiple unnamed registered types that are registered to the same interface. Now you can specify an override in your controller constructor using an attribute. My example is for a controller named MyController2 and I added the Dependency attribute with the name also specified above in the registration. So for this constructor a CustomerService type will be injected instead of the default CustomerServiceLoggingDecorator type. MyController1 will still use the default unnamed registration for ICustomerService which is type CustomerServiceLoggingDecorator.
public MyController2([Dependency("plainService")]ICustomerService service)
public MyController1(ICustomerService service)
There are also ways to do this when you manually resolve the type on the container itself, see Resolving Objects by Using Overrides. The problem here is that you need access to the container itself to do this which is not recommended. As an alternative you could create a wrapper around the container that you then inject into the Controller (or other type) and then retrieve a type that way with overrides. Again, this gets a bit messy and I would avoid it if possible.
Building upon Mark's second answer I'd look to registering the CustomerService with a InjectionFactory and only register it with the service type without it's interface like:
containter.RegisterType<CustomerService>(new InjectionFactory(
container => new CustomerService(containter.Resolve<IGenericRepository<Customer>>())));
This would then allow, as in Mark's answer, for you to register the logging object like:
containter.RegisterType<ICutomerService, CutomerServiceLoggingDecorator>(new InjectionConstructor(
new ResolvedParameter<CustomerService>()));
This is basically the same technique that I use whenever I require something to be lazily loaded as I don't want my objects to depend upon Lazy<IService> and by wrapping them in proxy allows me to only inject IService but have it resolved lazily through the proxy.
This will also allow you to pick and choose where either the logging object or the normal object is injected instead of requiring magic strings by simply resolving a CustomerService for your object instead of the ICustomerService.
For a logging CustomerService:
container.Resolve<ICustomerService>()
Or for a non-logging CustomerService:
container.Resolve<CustomerService>()

Unity suddenly fails to create class when I added an interface

In the process of decoupling some code and I extracted an interface for one of our classes, and mapped it using Unity like so
Container.RegisterType<IUserAuthorizationBC, UserAuthorizationBC>(
new Interceptor<InterfaceInterceptor>(), new InterceptionBehavior<PolicyInjectionBehavior>());
As you can see the class is UserAuthorizationBC and the interface is of course IUserAuthorizationBC. Once i did this I began to get an error in a class that I thought would not have mattered. The ctor for the class that now gives an error is as follows
public RoleAuthorizationService(IDataContractFactory factory,
UserAuthorizationBC businessProcessor)
: base(factory, businessProcessor)
{
_authBC = businessProcessor;
}
As you can see I haven't refactored it yet, I haven't even touched it, it was set up to get a concrete instance of UserAuthorizationBC and whoever created it is also injecting an IDataContractFactory which I did find mapped in our code base as you can see in following code snippet.
Container.RegisterType<IDataContractFactory, DefaultDataContractFactory>(
new Interceptor<InterfaceInterceptor>(),
new InterceptionBehavior<PolicyInjectionBehavior>());
I get an error from unity as follows
Microsoft.Practices.Unity.ResolutionFailedException: Resolution of the
dependency failed, type =
"HumanArc.Compass.Shared.Interfaces.Service.IRoleAuthorizationService",
name = "(none)".
Exception occurred while: Calling constructor Microsoft.Practices.Unity.InterceptionExtension.PolicyInjectionBehavior(Microsoft.Practices.Unity.InterceptionExtension.CurrentInterceptionRequest
interceptionRequest,
Microsoft.Practices.Unity.InterceptionExtension.InjectionPolicy[]
policies, Microsoft.Practices.Unity.IUnityContainer container).
Exception is: ArgumentException - Type passed must be an interface.
Now if I go comment out my mapping for IUserAuthorizationBC it will work fine again. I have no idea why.
actually I don't know why it ever works because if you look at the DefaultDataContractFactory it uses all generics which I would assume would always fail to resolve as at the time the unity doesn't know the type of T - see the class below.
public class DefaultDataContractFactory : IDataContractFactory
{
public DefaultDataContractFactory();
public virtual T Create<T>();
public virtual object Create(Type type);
public virtual Example<T> CreateExample<T>();
protected Type CreateFactoryType(Type instanceType);
}
So to sum things up there are two questions.
How does it even work in the first place before I added an interface for the IUserAuthorizationBC class and then added the mapping for unity - I would think that the IDataContractFactory would always blow it up.
Since it does work if I comment out the container mapping for IUserAuthorizationBC why does it stop working when I uncomment it - I would have thought it wouldn't make a bit of difference as this particular class always has been injected with a concrete instance of the UserAuthorizationBC
I thought I understood dependency injection fairly well - especially with unity but I am clearly missing the boat here.
I was going to make this a comment, but it's too long. Maybe your Unity container is configured for convention-based registrations, so your explicit registration is confusing matters. The IDataContractFactory/DefaultDataContractFactory pair needs to be explicity registered because the names don't follow the prescribed convention.
See if you have something like this in your code:
// This will register all types with a ISample/Sample naming convention
container.RegisterTypes(
AllClasses.FromLoadedAssemblies(),
WithMappings.FromMatchingInterface,
WithName.Default);
Prerequisite
Take a look at Interception using Unity. It looks like you are using interception with policy injection. Two conditions need to be met in order for a method to be intercepted. The policy needs to match on the method / type. And the type needs to opt-in to interception in the Unity registration by selecting an interceptor (InterfaceInterceptor, VirtualMethodInterceptor, or TransparentProxyInterceptor).
Answers
Commenting out that registration effectively opted-out that type from using interception.
You opted-in to interception but you told Unity to use interface interception. You are not resolving an interface, so it doesn't know how to generate a proxy for interception.
Possible solutions
Leave the registration as-is with the InterfaceInterceptor and update all constructors to use your new interface instead of the concrete type.
Change your new IUserAuthorizationBC registration to use VirtualMethodInterceptor and update any methods you want to be able to be intercepted to be virtual.
Change your new IUserAuthorizationBC registration to not specify an interceptor to effectively opt-out of interception.

C# logging "russian dolls effect" in constructors parameters

First, I am not sure that I use the good words to describe my problem, apologies (English is not my mother tong).
It is about adding loggers to a project.
As it was asked, there should be several loggers and they should to be defined "dynamically".
So we end up with classes that have a Logger property.
All constructors have though an extra parameter which is the logger instance passed to the constructor with the other business parameters. As we go deep inside the code, classes inside each other are using the same pattern to pass the logger instance.
Sure it works, but I am not happy with it.
What annoys me is that the logger does not belongs to the business logic.
Maybe there is nothing to do with it.
--
More precisely this is what I am working out for the moment :
There is the ILogger interface that defines the loggers functions (LogError(string msg) for example). Different Loggers will implement this interface.
There is the ILoggable interface that will be implemented by all classes that need to do logging. This interface has a property public ILogger LoggerPte
I use a static class LoggerUtility with a [ThreadStatic] field static ILogger CurrentLogger and a function :
public static void SetLoggerReference(ILoggable loggableClass)
{
loggableClass.LoggerPte = CurrentLogger;
}
Outside of the loggable class, the CurrentLogger is defined.
In the constructor of a loggable class, I have to call LoggerUtility.SetLoggerReference(this);
If found this way more elegant although it might be twisted, but I would like to know if it can be possible to go further...
I have just started to read about custom attributes, reflection and AOP. Can somebody give me a hand about how to use an attribute like [Loggable] to automatically make the constructor call the function SetLoggerReference(this) after the constructor without having explicitly to write it in the code.
If it is possible...
Did you hear about Dependency injection desgin pattern? Your original solution is simple constructor injection. Your final solution is Property injection and all your bussines objects need to have LoggerPte property. Please look at some solutions how to deal with dependency injection and build/create your business objects via dependecy injection container (the container will inject the LoggerPte property for you and you don't need to call your static method in each object constructor). I am using Unity Container (Microsoft solution) but you can find a lot of others.
I hope it's what you need.

How to create testable code using .Net IO classes?

I want to create unit testable code that mocks out the calls to the .Net System.IO classes, so I can really unit test instead of depending on the filesystem.
I am using the SystemWrapper classes to wrap around the BCL classes.
I am trying to get a simple example working to see whether a file exists.
The problem I am having is that injecting the dependency in the class doesn't work because instantiating the dependency (through StructureMap) requires knowing what constructor parameter to pass, which won't be available at that time, also there is no default constructor.
sample code:
// don't want to create dependency here like so
//IFileInfoWrap fileInfoWrap = new FileInfoWrap(filename);
// using service locator (anti-pattern?!) since it can't be
// injected in this class
var fileInfoWrap = ObjectFactory.GetInstance<IFileInfoWrap>(
new ExplicitArguments(new Dictionary<string, object>
{
{"fileName", filename}
}));
Console.WriteLine("File exists? {0}", fileInfoWrap.Exists);
What I don't like is that the dependency is not injected, ObjectFactory should not be here (but I see no other way of creating this).
The ExplicitArguments makes it messy and the argument-name is a magic-string.
For me to get this to work StructureMap config class needs to know explict which constructor I want to use ( I just started with StructureMap so this might not be the right way to set it up):
ObjectFactory.Initialize(x =>
{
x.Scan(scan =>
{
scan.AssembliesFromPath(".");
scan.RegisterConcreteTypesAgainstTheFirstInterface();
scan.WithDefaultConventions();
});
// use the correct constructor (string instead of FileInfo)
x.SelectConstructor(() => new FileInfoWrap(null as string));
// setting the value of the constructor
x.For<IFileInfoWrap>()
.Use<FileInfoWrap>()
.Ctor<string>("fileName")
.Is(#".");
});
Does anyone found a better solution to create testable code against the System.IO classes?
I know part of the problem is in the design of the System.IO classes.
An approach I've used very successfully is to roll my own proxy types for the types found in System.IO and other parts of the FCL. E.g. I want to take a dependency on System.IO.File. I create a library called System.IO.Proxies and add a concrete type File and an interface IFile. The interface IFile exposes members equivalent to all those which I require from System.IO.File and the concrete type implements those members by doing nothing other than forwarding method calls to System.IO.File. System.IO.Proxies is excluded from unit testing and code coverage. In my consuming assembly, I take a dependeny only on System.IO.Proxies and, specifically, I only take a dependency on IFile. This way I can mock this dependency easily and attain 100% code coverage for my consuming assembly.
(Note that this is a tailored version of my more general answer to a previous question.)

Categories

Resources