using Microsoft.Practices.Unity.Configuration;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using Unity;
using Unity.Resolution;
namespace Utils
{
/// <summary>
/// 服务定位器类,做依赖注入解析
/// </summary>
public class ServiceLocator
{
private readonly IUnityContainer container;
public ServiceLocator()
{
var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
container = new UnityContainer();
section.Configure(container);
}
public static ServiceLocator Instance
{
get { return new ServiceLocator(); }
}
public T GetService<T>()
{
return container.Resolve<T>();
}
public T GetService<T>(object overridedarguments)
{
var overrides = GetParameterOverride(overridedarguments);
return container.Resolve<T>(overrides.ToArray());
}
public object GetService(Type serviectype)
{
return container.Resolve(serviectype);
}
public object GetService(Type servicetype, object overridedarguments)
{
var overrides = GetParameterOverride(overridedarguments);
return container.Resolve(servicetype, overrides.ToArray());
}
private IEnumerable<ParameterOverride> GetParameterOverride(object overridearguments)
{
var overrides = new List<ParameterOverride>();
var argumenttype = overridearguments.GetType();
argumenttype.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)
.ToList()
.ForEach(property =>
{
var propertyvalue = property.GetValue(overridearguments, null);
var propertyname = property.Name;
overrides.Add(new ParameterOverride(propertyname, propertyvalue));
});
return overrides;
}
public T GetService<T>(ParameterOverrides parameters)
{
return container.Resolve<T>(parameters);
}
}
}
while(true)
{
//消息总线服务器地址
IEventBus result = ServiceLocator.Instance.GetService<IEventBus>(
new ParameterOverrides {
{ "connectionFactory",connectionFactory },
{ "context", ServiceLocator.Instance.GetService<IEventHandlerExecutionContext>() },
{ "exchangeName","s" },
{ "exchangeType","direct" },
{ "queueName","ss" },
{ "publisherorconsumer", 1 },
{ "autoAck",true}
});
}
现在的情况是,内存一直不停的增加,检查是由于循环里的这段代码产生的,请问怎么改代码,才能在每次用完 result后,销毁 result ,从而使内存不增长,保存平稳
可以把result定义在while循环外部
IEventBus result;
while(true)
{
result = ***;
}
循环里可以创建对象,不要创建对象的引用。否则GC是不会对这些引用进行清理的。
谢谢
也有可能不是rabbitmq导致的内存异常增长,可以在找几个重点方法,加上内存占用大小的输出来找找原因