0

I have an ASP.NET MVC 5 app (.NET Framework 4.8), using OWIN. The DI container is created in the startup and does it's job well in services and controllers. But I don't know of any way to resolve objects in the Application_Error event.

Startup class:

[assembly: OwinStartup(typeof(MyWebsite.Startup))]
namespace MyWebsite
{
    public class Startup {
        public void Configuration(IAppBuilder app) 
        {
            ServiceCollection services = new ServiceCollection();
            ...
            ContainerBuilder builder = new ContainerBuilder();
            builder.Populate(services);
            builder.RegisterType<MyLogger>().As<ILogger>().InstancePerLifetimeScope();
            ...
        }
}

Global.asax:

public void Application_Error(object sender, EventArgs e) 
{
//How to get an ILogger instance here?
}

Edit: My logging has a dependency on other services, so I cannot manually instantiate the logging class. I really need a resolver for MyLogger

fre_der
  • 83
  • 10
  • 2
    Does this answer your question? [How to inject dependencies into the global.asax.cs](https://stackoverflow.com/questions/7752023/how-to-inject-dependencies-into-the-global-asax-cs) – Ramil Aliyev 007 Feb 10 '21 at 13:54
  • Not really, that example shows how to manually instantiate a single MyLogger class inside an MVCApplication instance. But MyLogger depends on other injected objects as well, so I really need a way to resolve it. Otherwise, I would have to recreate the whole dependency tree of objects, and that beats the purpose of DI. – fre_der Feb 10 '21 at 14:06
  • 3
    "The class in your global.asax.cs is your Composition Root, so you can't (and shouldn't) inject anything into it from the outside." https://stackoverflow.com/a/7752308/8810311 – Ramil Aliyev 007 Feb 10 '21 at 14:11
  • I'm afraid that's right. I just need an alternative way to accomplish my logging needs when a global exception occurs. One solution might be to re-route to an error controller action, and log from there, but it doesn't seem right either. – fre_der Feb 10 '21 at 14:16
  • A few years ago, I also faced this problem. I searched a lot and I thinks this solution to be the only correct solution – Ramil Aliyev 007 Feb 10 '21 at 14:20
  • Yes, but it'll only work if your logger instance object doesn't need any extra dependencies from DI. Mine does. – fre_der Feb 10 '21 at 14:50

0 Answers0