I used the trick for a while to help with maintaining the audit trail. In or in front of the controller, I create a User that is somehow related to the request. I can use DI to create most of my application as single numbers, and I can just enter Func<User> , where I think I need User information. I get a user request on request from Func and can easily add audit information to everything.
This does not allow aggregating classes of the User domain and allows my DI container to act as a User management system.
Now I am using asp.net 5 and it is difficult for me to do the same. Honestly, I was never sure I could do this, but I'm used to it.
I am trying to do something like this:
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddScoped<IUser, User>(); services.AddSingleton<IDependantOnUser, DependantOnUser> services.AddScoped<Func<IUser>(c => c.GetRequiredService<IUser>); }
Then, in or in front of my controller, I create and populate a user instance.
public class ValuesController : Controller { public ValuesController(Func<User> userFunc) { user = userFunc();
Then, finally, I should have access to the user instance in my single object.
public class DependantOnUser : IDependantOnUser { public DependantOnUser(Func<User> userFunc) { user = userFunc();
But I can't get this to work. Before asp.net 5, I used Autofac to achieve this, but I was out of luck there. I tried playing with short / limited / single a little bit of no luck. I even tried to allow my own IServiceProvider and use it directly, and not just create a user with c => c.GetRequiredService<IUser>
Everything I do seems to work with the wrong instance of IServiceProvider . Is there a way to allow an instance from another ServiceProvider ? Any other suggestions would also be helpful.
Before suggesting, I simply register everything using AddScoped() , some of the objects between my presentation and persistence layers work much better than single ones.
Also, I would prefer not just to pass User information as a parameter for each method in my domain (we record it with almost every CRUD operation and pass it to most of the external calls that we make)