我有一个应用程序经常由于内存泄漏而停止。
ContainerFactory
班
public class ContainerFactory: IContainerFactory
{
public TTypeOfInstance GetInstance<TTypeOfInstance>()
{
return _container.Resolve<TTypeOfInstance>();
}
public TTypeOfInstance GetLoggerInstance<TTypeOfInstance>()
{
using (var lifetimeScope = _container.BeginLifetimeScope())
{
return lifetimeScope.Resolve<TTypeOfInstance>();
}
}
public void ScopedInstance<TTypeOfInstance>(Action<TTypeOfInstance> method)
{
using (var scopedInstance = _container.BeginLifetimeScope())
{
var instance = scopedInstance.Resolve<TTypeOfInstance>();
method(instance);
}
}
}
我正在创建
logger
在构造器中的原因如下
memory leak
失败
每隔一天
public MyClass(IContainerFactory containerFactory)
{
_containerFactory = containerFactory;
_logger = _containerFactory.GetInstance<ILogger>().ForContext(GetType());
}
logger = containerFactory.GetLoggerInstance<ILogger>().ForContext(GetType());
BeginLifetimeScope
是在做什么以及它如何帮助消除记忆问题?
那么,创建实例的方法正确吗?有没有更好的办法?
这是内存泄漏
这是个例外
框架版本:v4.0.30319
异常信息:System.AccessViolationException异常
在Serilog.Events.DictionaryValue…连接器(System.Collections.Generic.IEnumerable1>)
在Serilog.Capturing.PropertyValueConverter.TryConvertEnumerable(系统对象, Serilog.Parsing.Destructuring, 系统类型, Serilog.Events.LogEventPropertyValue拜里夫)
at Serilog.Capturing.PropertyValueConverter.CreatePropertyValue(System.Object, Serilog.Parsing.Destructuring, Int32)
at Serilog.Capturing.MessageTemplateProcessor.CreateProperty(System.String, System.Object, Boolean)
at serilog.Exceptions.Destructurers.ExceptionEnricher.Enrich(Serilog.Events.LogEvent,
Serilog.Core.ILogEventPropertyFactory)
public static IContainerFactory BuildContainer()
{
var containerFactory = new ContainerFactory();
var appSettings = ConfigurationManager.AppSettings;
var applicationName = appSettings.Get("applicationName");
builder.RegisterInstance(containerFactory).As<IContainerFactory>();
builder.Register(c => GetLoggerConfiguration(applicationName).CreateLogger()).As<ILogger>();
}
private static LoggerConfiguration GetLoggerConfiguration(string applicationName)
{
var config = new LoggerConfiguration();
if (!string.IsNullOrWhiteSpace(Settings.Default.ApplicationInsightsInstrumentationKey))
{
config = config.WriteTo.ApplicationInsightsEvents(Settings.Default.ApplicationInsightsInstrumentationKey, LogEventLevel.Error);
}
config = config.
Enrich.WithProperty("ApplicationName", applicationName).
Enrich.WithExceptionDetails().
Enrich.WithMachineName().
Enrich.WithProcessId().
Enrich.WithThreadId().
ReadFrom.AppSettings();
return config;
}