简体   繁体   中英

C# - Autofac resolving new instances in different classes

Just started using Autofac! I would like to use the same instance of Logger in multiple classes, but Autofac is giving me a new instance of Logger in different classes.

IocBuilder.cs

public static class IoCBuilder
{
    public static IContainer Container()
    {
        var logger = new LoggerConfiguration()
                .MinimumLevel.Verbose()
                .WriteTo.Console(outputTemplate: outputTemplate)
                    .WriteTo.File("logs/log-.log",
                                  outputTemplate: outputTemplate,
                                  rollingInterval: RollingInterval.Day)
                    .CreateLogger();

        // Container
        var builder = new ContainerBuilder();
        builder.RegisterInstance(logger).As<ILogger>().SingleInstance();
        builder.RegisterType<MyOtherClass>().SingleInstance();

        return builder.Build();
    }
}

MyOtherClass.cs

public class MyOtherClass
{
    public ILogger Logger {get; set; }
    public MyOtherClass(ILogger logger)
    {
         Logger = logger;
    }

    public void FirstMethod()
    {
        Logger.Information("MyOtherClass- FirstMethod");
    }

    public void SecondMethod()
    {
        Logger.Information("MyOtherClass - SecondMethod");
    }
}

Program.cs

public static IContainer Container
{
    get { return IoCBuilder.Container(); }
}

static void Main(string[] args)
{
    using (var scope = Container.BeginLifetimeScope())
    {
        var settings = Container.Resolve<ISettings>();
        var logger = Container.Resolve<ILogger>();
        logger.Information($"From program class: {settings.ToString()}"); // Prints log in log-20171217.log file

        var myOtherClass = Container.Resolve<MyOtherClass>();
        myOtherClass.FirstMethod(); // Prints log in log-20171217_1.log file
        myOtherClass.SecondMethod(); // Prints log in log-20171217_1.log file
    } // using scope   
} // void main

日志文件重复

I would like to use a single instance of the Logger class all over my application. Any help is greatly appreciated!

The problem is that you create a new instance of the container here:

public static IContainer Container
{
    get { return IoCBuilder.Container(); }
}

Every time you get a value of Program.Container , you get a new instance of the entire container. Every new instance of the container creates a new instance of the logger.

You have to cache the container in Program , like this:

private static IContainer _container = IoCBuilder.Container();

public static IContainer Container
{
    get { return _container; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM