Note that there are some explanatory texts on larger screens.

plurals
  1. POAccessing UnityContainer from AttributeHandler
    primarykey
    data
    text
    <p>I have Unity setup to intercept method calls when the method is decorated with a specific attribute. I want all Unity proxy objects to persist within each thread (rather than be transient).</p> <p>The issue is that the object created by the decoration attribute is created 'new' each time. I cannot see a way to access the UnityContainer from within the attribute. If I could, I would create the LogHandler as a per-thread entity and request it via Unity. (Does this even make sense though? Using Unity to resolve objects used in unity interception?).</p> <p>If you run this code, the count output by the logger is always '1'. To be clear, this 'LogHandler' is what I want to persist.</p> <p>How do you resolve objects via unity elsewhere in your code? Do you pass around the unity container? Is there a pattern I can use to request it from anywhere in my code?</p> <pre><code>using System; using Microsoft.Practices.Unity; using Microsoft.Practices.Unity.InterceptionExtension; namespace UnityTest2 { class Program { private static UnityContainer _uC; static void Main(string[] args) { _uC = new UnityContainer(); _uC.AddNewExtension&lt;Interception&gt;(); _uC.Configure&lt;Interception&gt;().SetInterceptorFor&lt;ICalc&gt;(new InterfaceInterceptor()); _uC.RegisterType&lt;ICalc, Calc&gt;( new PerThreadLifetimeManager() ); var c = _uC.Resolve&lt;ICalc&gt;(); Console.WriteLine(c.Add(3, 7)); Console.WriteLine(c.Sub(3, 7)); Console.ReadKey(); } } public class LogAttribute : HandlerAttribute { public override ICallHandler CreateHandler(IUnityContainer container) { // I want this to persist per thread return new LogHandler(); } } public class LogHandler : ICallHandler { private int runCount = 0; public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { runCount++; // this is always '1' Console.WriteLine(runCount); return getNext()(input, getNext); } public int Order { get; set; } } public interface ICalc { int Add(int x, int y); int Sub(int x, int y); int Mul(int x, int y); } public class Calc : ICalc { [Log] public int Add(int x, int y) { return x + y; } [Log] public int Sub(int x, int y) { return x - y; } public int Mul(int x, int y) { return x * y; } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload