Skip to content

Instantly share code, notes, and snippets.

@sunnamed434
Created October 13, 2022 12:41
Show Gist options
  • Save sunnamed434/e94dfe9f4ac5993eb3b08330485281e1 to your computer and use it in GitHub Desktop.
Save sunnamed434/e94dfe9f4ac5993eb3b08330485281e1 to your computer and use it in GitHub Desktop.
CLI + GUI Injecting Serilog through Host with Autofac
var container = new BitMonoApplication().RegisterModule(new BitMonoModule(configureLogger =>
{
configureLogger.WriteTo.Async(configureSinkConfiguration =>
{
configureSinkConfiguration.Console();
});
})).Build();
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp<App>()
.ConfigureFonts(fonts =>
{
fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
});
builder.ConfigureContainer(new AutofacServiceProviderFactory(), configure =>
{
configure.RegisterModule(new BitMonoModule(configureLogger =>
{
// Логирование для GUI
}));
});
public class BitMonoApplication : IApplication
{
private readonly ContainerBuilder m_ContainerBuilder;
private readonly List<IModule> m_Modules;
public BitMonoApplication()
{
m_ContainerBuilder = new ContainerBuilder();
m_Modules = new List<IModule>();
}
public IApplication Populate(ICollection<ServiceDescriptor> descriptors)
{
m_ContainerBuilder.Populate(descriptors);
return this;
}
public IApplication RegisterModule(IModule module)
{
m_Modules.Add(module);
return this;
}
public AutofacServiceProvider Build()
{
foreach (var module in m_Modules)
{
m_ContainerBuilder.RegisterModule(module);
}
var container = m_ContainerBuilder.Build();
return new AutofacServiceProvider(container.Resolve<ILifetimeScope>());
}
}
public class BitMonoModule : Module
{
private readonly Action<LoggerConfiguration> m_ConfigureLogger;
private readonly Action<ConfigurationBuilder> m_ConfigureConfiguration;
public BitMonoModule(
Action<LoggerConfiguration> configureLogger = default,
Action<ConfigurationBuilder> configureConfiguration = default)
{
m_ConfigureLogger = configureLogger;
m_ConfigureConfiguration = configureConfiguration;
}
protected override void Load(ContainerBuilder containerBuilder)
{
var currentAssemblyDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
var file = Path.Combine(currentAssemblyDirectory, "logs", "bitMono-{HalfHour}.log");
containerBuilder.Register<ILogger>((_, _) =>
{
var loggerConfiguration = new LoggerConfiguration();
m_ConfigureLogger?.Invoke(loggerConfiguration);
return loggerConfiguration
.WriteTo.Async((c) =>
{
c.RollingFile(file, shared: true);
})
.CreateLogger();
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment