2
votes

In another stackoverflow question MVC5 IoC and Authentication the first answer states the author uses Dependency Injection to inject the IPrincipal. I would love to do this for my assemblers so that I don't have to pass the current user (IPrincipal) from the controller.

Can anyone give an example of how to use DI to inject the IPrincipal in C# MVC5? Below is the IoC I first want to implement it in. Added after first answer given.

    public class ViewModelAssemblersInstaller : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            container.Register(
                Component.For<IAspNetUserAssembler>()
                .ImplementedBy<AspNetUserAssembler>());
        }
    }
2

2 Answers

7
votes

For Castle Windsor, it's something like:

container.Register(Component.For<IPrincipal>()
  .LifeStyle.PerWebRequest
  .UsingFactoryMethod(() => HttpContext.Current.User));
6
votes

Its going to be dependent on your IoC container... for me, I use Unity, and in my container registration I'm able to do the following:

container.RegisterType<IPrincipal>(new InjectionFactory(u => HttpContext.Current.User));

Using the InjectionFactory, unity will execute the lambda to return the current HttpContext.Current.User at the time of constructor injection. I'm also able to use the same type of registration in my non web applications, instead referencing the Thread.CurrentPrincipal.