C# - Autofac解析不同类中的新实例

时间:2017-12-17 18:35:00

标签: c# singleton autofac

刚开始使用Autofac!我想在多个类中使用相同的Logger实例,但Autofac在不同的类中为我提供了一个新的Logger实例。

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

Duplicate log files

我想在我的应用程序中使用Logger类的单个实例。非常感谢任何帮助!

1 个答案:

答案 0 :(得分:5)

问题是你在这里创建了一个新的容器实例:

    def create_widget(self, cont, args):
        if(args[0] == 'Button'):
            self.create_button(cont, args)
        elif(args[0] == 'Entry'):
            self.create_entry(args)
        elif(args[0] == 'CheckBox'):
            self.create_checkbox(args)
        elif(args[0] == 'Label'):
            self.create_label(args)
        else:
            print("Invalid Argument while creating Widget")

    def create_entry(self, args):
        if(args[4] == True):
            entry = tk.Entry(self, font=FONT, width=args[1])
            entry.place(x=args[2],y=args[3])
        else:
            entry = tk.Entry(self, font=FONT, width=args[1], show = '*')
            entry.place(x=args[2],y=args[3])

    self.create_widget(controller, ["Entry", 21, 135, 30, True])
    self.create_widget(controller, ["Entry", 21, 135, 60, False])

每次获得public static IContainer Container { get { return IoCBuilder.Container(); } } 的值时,都会获得整个容器的新实例。容器的每个新实例都会创建一个新的记录器实例。

您必须将容器缓存在Program.Container中,如下所示:

Program