I am using StructureMap for resolving the Dependency in my Projects, I am getting multiple Proxy instances for a Singleton Registration while resolving, below are the code
in StartUp.cs file I am creating a new container and adding one Policies as per below code
var structuremapContainer = new Container();
structuremapContainer.Configure(
x => x.Policies.Interceptors(new ProfilerInjectorPolicy()));
ProfilerInjectorPolicy.cs
public class ProfilerInjectorPolicy : IInterceptorPolicy
{
private static readonly ProxyGenerator _proxyGenerator = new();
private static readonly MethodInfo _genericProxyDelegate =
typeof(ProfilerInjectorPolicy)
.GetMethod("GetProxy", BindingFlags.NonPublic | BindingFlags.Static);
public string Description => "Profiler injector policy";
public IEnumerable<IInterceptor> DetermineInterceptors(
Type pluginType, Instance instance)
{
var interceptorType =typeof(FuncInterceptor<>).MakeGenericType(pluginType);
var method = _genericProxyDelegate.MakeGenericMethod(pluginType);
var arg = Expression.Parameter(pluginType, "x");
var methodCall = Expression.Call(method, arg);
var delegateType = typeof(Func<,>).MakeGenericType(pluginType, pluginType);
var lambda = Expression.Lambda(delegateType, methodCall, arg);
var interceptor =
Activator.CreateInstance(interceptorType, lambda, string.Empty);
yield return interceptor as IInterceptor;
}
private static T GetProxy<T>(object service)
{
var allInterfaces = service.GetType().GetInterfaces();
var additionalInterfaces = allInterfaces.Except(new[] { typeof(T) });
var result = _proxyGenerator.CreateInterfaceProxyWithTargetInterface(
typeof(T),
additionalInterfaces.ToArray(), service, new ProfilerInterceptor());
return (T)result;
}
}
Problem is, when I am Registering as a Singleton with Func<> Object, The GetProxy() method call everytime while resolving the dependency, I have tested that it's only calling the GetProxy() method, but not calling the constructor of class except first time.
yield return Registration.AsSingleton(typeof(IProduct), () => new Product());
This return the new Proxy instance on every time when calling Container.GetInstance<IProduct>().
yield return Registration.AsSingleton<IProduct, Product>(); This call only once the GetProxy() method on every time when calling Container.GetInstance<IProduct>().
Can anyone help me why I am getting this issue, is there anything I need to change in my code.
// This should call once the GetProxy() method like
yield return Registration.AsSingleton<IProduct, Product>();
yield return Registration.AsSingleton<IProduct, Product>();