We were unable to load Disqus. If you are a moderator please see our troubleshooting guide.

Kenny Eng • 6 years ago

This article is good but I'm using Castle Windsor.

Do you have the full source code of Castle Windsor?
Because the link you provided is not a full source code

var container = DIContainer.GetConfiguredContainer(); <----- where does DIContainer comes from?

Andrew Kuzovov • 6 years ago

Yes, this file is part of a private project.
DIContainer.GetConfiguredContainer() just returns instance of your configured IWindsorContainer.

internal class DIContainer
{
private static readonly Lazy<iwindsorcontainer> Container = new Lazy<iwindsorcontainer>(() =>
{
var container = new WindsorContainer();
RegisterTypes(container);
return container;
});

private static void RegisterTypes(IWindsorContainer container)
{
var sqlServerConnectionString = "...";

container.Register(
Component
.For<iproductrepository>()
.ImplementedBy<dataaccess.mssql.productrepository>()
.DependsOn(Dependency.OnValue<string>(sqlServerConnectionString.ConnectionString))
.LifestyleTransient(), ...)
}
}

Kenny Eng • 6 years ago

Thank you for the reply.

So I don't need this line of code
var container = DIContainer.GetConfiguredContainer();
if I follow your code right?

And is your code implement in StartUp.cs? Can I implement in different .cs file?

Andrew Kuzovov • 6 years ago

You can replace DIContainer.GetConfiguredContainer() entirely with your creation and initialization method, which returns instance of configured IWindsorContainer.

Yes you can use another file and class name. The main thing is the OWIN attribute:
[assembly: OwinStartup(typeof(Startup))]
And presense of method
public void Configuration(IAppBuilder app)

Kenny Eng • 6 years ago

Thanks Andrew. The problem is solved:
https://github.com/aspnetbo...
Because I'm using AspNet Boilerplate framework, and they implemented Castle Windsor already. It's my bad, I should ask them instead of asking here. Thanks by the way.

But there is another problem is identity claims are not updated. And I'm waiting for their answer and doing some research on my own on this problem.

Tim Baart • 9 years ago

This worked great for me, but after doing some testing I found out that the UserManager returned by the IOwinContext is always the same object. It gets created by the Unity Container the first time it is used, and will never be disposed. I did add this line to the MVC Activator:

Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));

Yet the UserManager is not resolved per request.

The UserManager used as arguments in Controllers (which are part of the WebApi activator, instead of the Mvc Activator) do get resolved every request. I managed to set that up right.

How do I get this to work? Or rather - is it even necessary to get this to work? Considering the UserManager used by Identity is only used to read, not to write, is there any harm in having it only be resolved once?

Thanks for the article nonetheless. Saved me a lot of trouble!

trailmax • 8 years ago

Sorry, somehow I have missed your comment and noticed only now.

I have seen other people reporting the same problem before, however I have not done anything with this to prove the statement.

But I have traced the source code where UserManager resolved from IOwinContext and how it is used. I can confirm that UserManager in that case is only used to read data and never writes (see here https://aspnetidentity.code...

So there is no harm in having this UserManager to be a singleton. As long as you resolve UserManager for your controllers from the container and that is scoped per request.

citoyenLambda • 6 years ago

Thank you for this article.
The problem (there is always at least one) of the singleton come from entity framework. As a singleton the context is never recycled =>
- it will always grow in memory and, the worst imho,
- if you update directly the database (to validate an email for example by sql) for "an already loaded in the context user" the modification will never reach you application until you restart it...

trailmax • 6 years ago

DbContext should never be a singleton and it is never configured as one. Even default implementation from Microsoft template is using it per request.

citoyenLambda • 6 years ago

sorry, I miss read your article and miss configure unity. All is perfect now.

trailmax • 6 years ago

Ah, good! glad you got it sorted!

Felipe Correa • 8 years ago

Facing the same problem but with my EntitiesContext. I have been unable to get an instance in a Per Request Basis :-/

Did you get around this?

trailmax • 8 years ago

Is this causing troubles? see my comment above.

Felipe Correa • 8 years ago

Yeah, it is still causing problems and I figured what my problem is. I still saw the error because my controller actions are "async".

Do you know how to correctly configure the lifetime of an object inside unity when it is going to be injected after an "async" function is called?

trailmax • 8 years ago

sync or async, it should not matter to Unity. Have a look on this answer http://stackoverflow.com/a/... for scoping ideas. Unity is not my container of choice - I don't know any better.

Felipe Correa • 8 years ago

It didn't work with any of the options I have found including your suggestion... I don't know what to do to make it work properly. There should be a new instance with every request but it seems to be broken somehow.

Ivan Limansky • 8 years ago

Is this still an issue with the latest Git codebase?

Isn't this logic enforcing the per request lifetime?
// Configure the db context, user manager and signin manager to use a single instance per request
app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<applicationusermanager>());
app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<applicationsigninmanager>());

Thanks!

Bob • 9 years ago

Instead of
internal static IDataProtectionProvider DataProtectionProvider { get; private set; }

It's better to inject the `IDataProtectionProvider dataProtectionProvider` to ApplicationUserManager class and then at start up we can configure the IoC like this:

private void configureAuth(IAppBuilder app)
{
SmObjectFactory.Container.Configure(config =>
{
config.For<idataprotectionprovider>().Use(()=> app.GetDataProtectionProvider());
});

trailmax • 9 years ago

Yes, that's a good suggestion. I have thought of improving this bit, but did not pay enough attention.

Mike Dymond • 9 years ago

If you where to do this in Unity how would you configure the container, given that you do not currently have access to app in the RegisterTypes method?

trailmax • 9 years ago

I've just tried and got it working easily:

See this line for registration: https://github.com/trailmax...

And then you just inject IDataProtectionProvider into ApplucationUserManager: https://github.com/trailmax...

Mike Dymond • 9 years ago

OK, I had a play and got it working. This is my config code in Startup.Auth.

var container = DependencyResolver.Current.GetService<iunitycontainer>();
container.RegisterInstance(typeof (IDataProtectionProvider), null, app.GetDataProtectionProvider(), new TransientLifetimeManager());

I don't like the fact that I now have DI configuration in two separate places, but I can't see how that can be helped, unless I moved all the config here or somehow injected app into the existing config code.

Also I changed how my code gets hold of the container. (I really hate static methods!)

In case you didn't know (I seems to remember you said the Unity was not you DI of choice), whenever you create a Unity container, the first thing it does is register itself with itself. In other words you can use the container to get an instance of the container. So seeing as I already have access to DependancyResolver I can use that to get the container and then add config.

Thanks again for your help.

Cheers Mike

trailmax • 9 years ago

Correct, I've never used unity before writing this article. But most of the containers can resolve themselves if you ask for `IContainer` or similar interface.

Unfortunately with this set up of OWIN and DataProtectionProvider, whatever you do will be a fudge. As I've done originally - save a reference as a global static, then re-use it. You can train your container to access this global static (probably as a delegate, not directly in case DI is configured before OWIN) and inject instance into consumers. You can re-configure container (as you have done above). All these seem to be a little hacky. But as long as no pink fluffy bunnies die over your code, it is all good -) So I would not waste much time over perfecting this issue.

Mike Dymond • 9 years ago

Really? I have just tried to do what you suggest and am getting compile errors. The line

UnityConfig.GetConfiguredContainer().RegisterInstance(app.GetDataProtectionProvider());

fails because RegisterInstance has 4 parameters but is only called with 1.

Also, since we are not registering this instance against an interface how can the DI container inject the correct object into the constructor of ApplicationUserManager?

Once again, thanks for answering my questions and I am sure I am just missing something obvious.

Cheers Mike

trailmax • 9 years ago

With the build fail, make sure you have namespace `Microsoft.Practices.Unity` added to the file - this `RegisterInstance` is actually an extension method coming from `Microsoft.Practices.Unity.UnityContainerExtensions`

As for lack of Interface, Unity can do this - it registers all the classes for their implemented interfaces, also it can resolve concrete classes without implicit registration. Something that can be very useful. Or very scary when you have a few implementations of the same interface.

Mike Dymond • 9 years ago

Right, of course, hate it when that happens. All that that extension method does is exactly what I did in my code, except that is used the ContainerControlledLifetimeManager (i.e. a singleton) whereas I used TransientLifetimeManager, which given that we are registering an instance is correct.

Derek Flenniken • 9 years ago

Thanks! I was nearly there, but this was really helpful. For the Autofac fans:

https://gist.github.com/3nt...

trailmax • 9 years ago

Great! Added your gist to list of links on the top.

Robert Sandona • 8 years ago

Thanks for the great article.
To help anyone using Ninject, here is the bindings I used.

kernel.Bind<dbcontext>().To<efdbcontext>(); //must not be in request scope -> owin db disposed error

kernel.Bind<applicationusermanager>().ToSelf().InRequestScope();

kernel.Bind<iauthenticationmanager>().ToMethod(c => HttpContext.Current.GetOwinContext().Authentication);

kernel.Bind<iuserstore<applicationuser>>().To<userstore<applicationuser>>().InRequestScope();

disqus_cRXF13od5I • 8 years ago

Hi Robert,

I am trying to use this with nijnect, but when making the calls to get an Token using the Oauth GrantResourceOwnerCredentials with OWIN , when making FindByNameAsync call it fails with the error:

Object name: 'ApplicationUserManager'.]
Microsoft.AspNet.Identity.UserManager`2.FindByNameAsync(String userName) +168
Microsoft.AspNet.Identity.<>c__DisplayClass1`1.<RunSync>b__0() +53
System.Threading.Tasks.Task`1.InnerInvoke() +79
System.Threading.Tasks.Task.Execute() +110
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +144
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +84
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +49
Microsoft.AspNet.Identity.AsyncHelper.RunSync(Func`1 func) +412

Could you please give an advice?

Robert Sandona • 8 years ago

Sorry, I can't tell from looking at your stack trace. If you still haven't found it, try posting a question about it on stack overflow. Make sure you include the exception message not just the stack trace and include a link back to this article.

Daniel Mackay • 8 years ago

Awesome article. Thanks mate!

Wojciech Sura • 8 years ago

Thanks for the article! You cut me a lot of work.

Mubeen • 8 years ago

This article helped me a lot to configure and use Unity with Owin based identity. Thank you very much! Much appreciated.

Milad Ashrafi • 9 years ago

Super LIKE

Alan Wolman • 9 years ago

Thanks for this post - getting Unity and Identity framework working seamlessly without this info would have been very hairy.

Roger • 9 years ago

Hi Max:

Thanks so much for this. I am trying to take an app that I have which uses StructureMap and upgrade it to use the Identity framework.

I am having problems figuring out how to translate the following statement into StructureMap :

container.RegisterType<iuserstore<applicationuser>, UserStore<applicationuser>>(new InjectionConstructor(typeof(ApplicationDbContext)));

Wondering if you or someone looking at this might be able to give me ah hand.

Thanks,
Roger

Craig Cronin • 9 years ago

Luckily came across this post even though I was using structuremap, the concepts saved me after 5 hours of debugging :)

Anon • 9 years ago

Awesome!

temporaryuser381 • 9 years ago

first of all, thank you for this awesome post. It really helped me save lots of time.
I just have one little problem, hopefully you can help me. I want to access my DBContext instance during onValidateIdentity Callback execution (during SecurityStampValidation). But since i am creating DbContext Per Request we can't access it there. Because, this callback is executed in IIS pipeline even before HttpContext is created. Can you please guide me how would i solve this problem?

trailmax • 9 years ago

he, that's a good one!
I have opted into manual creation of DbContext just for that case. I mean I did not use DI container to create my object, but done old-school `new DbContext("connectionString")`. One of the reasons for that you stated yourself. In 2 of my projects I ended up with cyclic dependency (on IPrincipal) that I had to break somehow and not using a container was a good solution.

In SecurityStampValidation event, DbContext is only used for reading ApplicationUsers table and comparing security stamp in cookie with the one in DB. No writing happens there. So there is no danger of having multiple DbContext instances - one early in the pipeline for Identity, another one from your DI container for you operations.

Sometimes DI containers only frame you in a box. One needs to learn when to use it and when to break free - this is the case when you need to break free -)

temporaryuser381 • 9 years ago

thnx.

Gabriele Gaggi • 9 years ago

Thanks a lot! You save my life! :-)

kubicek • 9 years ago

thanks a lot for a very clear and detailed post trailmax! you just saved me next couple hours of googling... this serviceLocator pattern introduced by Owin by default has bugged me on the project I am working on for weeks now and finally I was able to clear the mess. awesome post

trailmax • 9 years ago

Yep, Owin service locator is a bit eye-brow raising. But it is how Identity uses Owin. Natively Owin is just a dictionary of objects. See second half of this post http://tech.trailmax.info/2... for DI in OWIN and another second half of this post http://tech.trailmax.info/2... where Identity is using the service locator.

Mike Harrison • 9 years ago

thank u for your fantastic post , i have one question , since i cant use depency injetion with attribute filters , if i want to force a loged in user to log out , how can i do this in this enviement ?

trailmax • 9 years ago

Logging users out are easy. Logging-in and logging-out are a function of IAuthenticationManager. And that is provided by OWIN from HttpContext.GetOwinContext().Authentication.

So you attribute should will look like this: https://gist.github.com/tra...

However, this attribute seems a bit out of place to me. Logging out is either done by user himself - a specific action. Or as a result of some action that was performed by a user - part of the action and should be done specifically in the action, not as an attribute.

And to do DI into controller/action attributes I used this trick: create an empty marker attribute that only inherits Attribute class. Apply this attribute on controllers/actions when you need. Create a global filter (where you can do constructor injections) and apply them globally in FilterConfig.cs. On every action execution check if controller/action has the marker attribute applied through reflection. If your attribute is present, execute your action. No marker -> nothing happens. But beware that instances of filters live across many requests and most of MVC dependencies (especially EF DbContext) should not live longer than a request and lifescope of objects can be mismatched, creating "captive dependency" problem. I can find you articles to read if you need to solve this problem - let me know.

ardalis • 9 years ago

Why aren't you DI-ing EmailService and SmsService in ApplicationUserManager?

trailmax • 9 years ago

1. I'm lazy
2. I'm not implementing them, so no point in having them injected
3. Solution is incomplete
Pick one, or two, or three -)

Honestly, I've started doing it, but abandoned because saw no point in doing it at this moment. My thoughts was that if you start implementing EmailService/SmsService and they have dependency, chances that you know what you are doing are high and you don't need this article.

ardalis • 9 years ago

I ask not to be critical, but because it's causing me problems. I have the Identity classes pulled out of my Web project into an Infrastructure project, and since ApplicationUserManager doesn't (at least for now) know about my container nor expect an email service as a constructor dependency, it's difficult to DI one. I'm guessing the answer here is to make it a constructor parameter.

Thanks! I'm using StructureMap, by the way. If I end up producing anything worth sharing I'll add a comment and link to a GitHub repo.