We recently upgraded Microsoft's Unity in our project from version 3.5.1404 to 5.8.6. With only a few minor adjustments in our code this upgrade seemed to go pretty easy. It resolves all our registered instances without a problem. However, we also use Unity's Interception-mechanism to cache some results that a method returns in AOP-style. This cache mechanism is broken since the upgrade and we can't figure out why. Apparently, our attributes are no longer called when a decorated method is called.
It currently works as follows. We register the interception like this:
var container = new UnityContainer();
container.RegisterType<IService, Service>(some_lifetime);
container.AddNewExtension<Interception>();
container.Configure<Interception>()
.SetInterceptorFor(typeof(IService), new InterfaceInterceptor());
In the Service class, which implements IService we have a method that is decorated with a custom Cache attribute, like this:
public class Service : IService {
[Cache(..)]
public Result SomeMethod() {
// Some code
}
}
And lastly, our custom Cache attribute which inherits from Unity's HandlerAttribute:
public class CacheAttribute : HandlerAttribute
{
// ctor
public override ICallHandler CreateHandler(IUnityContainer container)
{
return new CacheCallHandler(container, and, some, more);
}
}
When method SomeMethod used to be called with version 3.5.1404 the attribute was called first, but since 5.8.6 it no longer calls this attribute. The code however, does compile. The changes we had to make to make it compile are mostly changes in usings. Like Microsoft.Practices.Unity.InterceptionExtension which changed to Unity.Interception.PolicyInjection.Policies.
We can't figure out why this mechanism is no longer working. And even after extensive research on the internet, we can't find a way to get this to work. Any suggesties would therefore be greatly appreciated!
I got in your exact same situation while trying to refresh some legacy code. I got it working with:
Changing:
config.SetInterceptorFor(myType, new InterfaceInterceptor()); for
config.SetInterceptorFor(myType, new TransparentProxyInterceptor());
Registering the class that inherits from HandlerAttribute
Container.RegisterType<MyHandlerAttribute>(new PerRequestLifeTimeManager());
Register each type to intercept with special InjectionMembers:
Container.RegisterType<MyClassToBeIntercepted>(
new Interceptor<TransparentProxyInterceptor>(),
new InterceptionBehavior<PolicyInjectionBehavior>()
);
Related
We're using Prism.DryIoc.Forms to create apps with Xamarin.Forms. To minimize the startup time of the app we are using the Lazy<> pattern for classes with a lot of dependencies.
This used to work fine with Prism.Unity.Forms. However, I can't get it to work with Prism.DryIoc.Forms. Any help would be appreciated.
The code is as follows. We have a page view model like this:
public class MySamplePageViewModel
{
private readonly Lazy<ISomeClass> _lazySomeClass;
public MySamplePageViewModel(Lazy<ISomeClass> lazySomeClass)
{
_lazySomeClass = lazySomeClass;
}
public void SomeMethod()
{
_lazySomeClass.Value.DoIt(); //throws exception
}
}
However, after the page view model is being instantiated, when calling _lazySomeClass.Value we get an exception with message "Container is no longer available (has been garbage-collected).".
It seems to be related to how Prism resolves the view model, because when calling the following it works fine:
var container = (Application.Current as PrismApplicationBase<IContainer>).Container;
var lazySomeClass = container.Resolve<Lazy<ISomeClass>>();
lazySomeClass.Value.DoIt(); //works fine
we're doing the registration like this:
container.Register<ISomeClass, SomeClass>(Reuse.Singleton);
container.RegisterTypeForNavigation<MySamplePage, MySamplePageViewModel>("MySamplePage");
The problem should be fixed in v2.10.3.
Therefore the next logical step is to ask Prism.DryIoc.Forms maintainers to update to the latest DryIoc version.
I'm trying to implement the Identity system in an ASP.NET Core app (RC2 libraries) and there is a particular hangup that is driving me crazy.
First of all, I am not using EntityFramework. I'm not even using SQL. I'm backing up to RavenDB, so I need the implementation to be very specific to that; Which isn't a problem.
So I designed a RavenUserStore class, and it looks like this;
public class RavenUserStore<TUser> :
IUserStore<TUser>,
IUserLoginStore<TUser>,
IUserPasswordStore<TUser>,
IUserRoleStore<TUser>,
IUserSecurityStampStore<TUser>,
IUserClaimStore<TUser>,
IUserLockoutStore<TUser>,
IUserTwoFactorStore<TUser>,
IUserEmailStore<TUser> {
// ...
}
Works great on its own. I've implemented all the methods, etc. It's wonderful. Very clean and efficient.
Now, I go over to my web application and wire things up;
services.AddTransient<ILookupNormalizer>(s => new LowerInvariantLookupNormalizer());
services.AddTransient<IPasswordHasher<Member>>(s => new PasswordHasher<Member>());
services.AddTransient<IUserStore<Member>, RavenUserStore<Member>>();
services.AddIdentity<Member, Role>(o => {
o.Password.RequiredLength = 6;
o.Password.RequireDigit = true;
o.Password.RequireLowercase = false;
o.Password.RequireUppercase = false;
})
.AddUserStore<RavenUserStore<Member>>()
.AddRoleStore<RavenRoleStore<Role>>();
So I go make a controller to use this, per all the samples I've seen, and the very core sample from the Identity Framework Github Repository
//... [PROPERTIES]...//
public AccountController(UserManager<Member> userManager, SignInManager<Member> signInManager) {
// ... [attach constructor parameters to properties] ...//
}
Alright, so I inspect the classes carefully.
UserManager<T> has a property Store,which is a type of IUserStore<T>.
So theoretically.. if the dependency injection resolves types of IUserStore<T> to RavenUserStore<T> when they are injected through a constructor.. shouldn't that mean that the UserManager<T> gets a RavenUserStore<T> as its Store property?
I thought it would too; But when I call methods on the UserManager, it DOES NOT call the ones on my RavenUserStore. Why is this? What can I do?
Do I really have to ALSO make a custom UserManager class and do all of those methods AGAIN?
You need to add your own custom providers before calling services.AddIdentity(). Internally, AddIdentity uses TryAddScoped() which only adds the default items if they don't already exist in the services container.
So just putting the call to AddIdentity() after you registered all your custom implementations should mean that they will take precedence as you expect.
I have the following code:
Unity Container:
Settings settings = CreateSettings();
container.RegisterInstance(settings)
.RegisterType<MyHttpHandler>(new InjectionProperty[]
{
// How do I tell Unity to inject my settings created above?
new InjectionProperty("Settings", new ResolvedParameter(????))
});
MyHttpHandler:
public class MyHttpHandler: IHttpHandler
{
public MyHttpHandler()
{
IoC.Inject(this);
}
public Settings Settings
{
get;
set;
}
}
How do I tell Unity to inject the settings? This works just fine with interfaces but not sure how to proceed here.
Any help is appreciated.
It just goes off the type. You've registered an instance for the Settings class, so you just need to tell it to inject that type:
container.RegisterInstance(settings)
.RegisterType<MyHttpHandler>(
new InjectionProperty("Settings", new ResolvedParameter<Settings>());
(Note that you don't need the extra array, RegisterType takes a variable parameter list.)
Since this is a common requirement, there are shorthands you can use. First off, if you're resolving a dependency and you just need the default (non-named) registration, you don't need to use ResovledParameter, you can just pass the type object:
container.RegisterType(settings)
.RegisterType<MyHttpHandler>(
new InjectionProperty("Settings", typeof(Settings));
But, we can also go simpler than that. If you're using the default for a property based on the type, you don't need to pass the value at all - the container will simply use the type of the property. So you can just say:
container.RegisterType(settings)
.RegisterType<MyHttpHandler>(
new InjectionProperty("Settings"));
and the container will figure it out.
I'm a first-time user of the AOP features of Unity 2.0 and would like some advice. My goal is to be able to log method calls in an ASPX page, like so:
public partial class Page2 : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[Log]
private void Testing()
{
}
}
Here is the code for the LogAttribute:
public class LogAttribute : HandlerAttribute
{
public override ICallHandler CreateHandler(IUnityContainer container)
{
return new LogHandler(Order);
}
}
Now the LogHandler:
public class LogHandler : ICallHandler
{
public LogHandler(int order)
{
Order = order;
}
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
string className = input.MethodBase.DeclaringType.Name;
string methodName = input.MethodBase.Name;
string preMethodMessage = string.Format("{0}.{1}", className, methodName);
System.Diagnostics.Debug.WriteLine(preMethodMessage);
return getNext()(input, getNext);
}
public int Order { get; set; }
}
The problem I have is how to use the [Log] attribute. I've seen plenty of example of how to configure the interception settings, for example:
container.AddNewExtension<Interception>();
container.Configure<Interception>().SetDefaultInterceptorFor<ILogger>(new InterfaceInterceptor());
But this implies that I have an interface to intercept, which I don't. I have the ASPX page which uses the [Log] attribute.
so how can I configure Unity to make use of the [Log] attribute? I've done this before using PostSharp and would like to be able to use Unity to do the same.
Cheers.
Jas.
You're unfortunately not going to get this to work in an ASP.NET page with Unity interception.
Unity interception uses a runtime interception model. Depending on the interceptor you choose, you'll either get a subclass with virtual method overrides to call the call handlers (VirtualMethodInterceptor) or a separate proxy object (Interface or TransparentProxyInterceptor) which execute the call handlers and then forward to the real object.
Here's the issue - ASP.NET controls creation and calls to your page, and there's no easy way to hook into them. Without controlling the creation of the page object, you can't use the VirtualMethodInterceptor, because that requires that you instantiate a subclass. And you can't use the proxy version either, because you need ASP.NET to make calls through the proxy.
PostSharp gets around this because it's actually rewriting your IL at compile time.
Assuming you could hook into the creation of the page object, you'd have to use the VirtualMethodInterceptor here. It's a private method, so you want logging on "self" calls (calls from one method of the object into another method on the same object). The proxy-based interceptors can't see those, since the proxy is a separate instance.
I expect there is a hook somewhere to customize how ASP.NET creates object - BuildManager maybe? But I don't know enough about the details, and I expect it'll require some pretty serious hacking to get work.
So, how do you get around this? My recommendation (actually, I'd recommend this anyway) is to use the Model-View-Presenter pattern for your ASP.NET pages. Make the page object itself dumb. All it does is forward calls to a separate object, the Presenter. The Presenter is where your real logic is, and is independent of the details of ASP.NET. You get a huge gain in testability, and you can intercept calls on the presenter without all the difficulty that ASP.NET gives you.
i have a HttpModule that creates an CommunityPrincipal (implements IPrincipal interface) object on every request. I want to somehow store the object for every request soo i can get it whenever i need it without having to do a cast or create it again.
Basically i want to mimic the way the FormsAuthenticationModule works.
It assigns the HttpContext.User property an object which implements the IPrincipal interface, on every request.
I somehow want to be able to call etc. HttpContext.MySpecialUser (or MySpecialContext.MySpecialUser - could create static class) which will return my object (the specific type).
I could use a extension method but i dont know how to store the object so it can be accessed during the request.
How can this be achieved ?
Please notice i want to store it as the specific type (CommunityPrincipal - not just as an object).
It should of course only be available for the current request being processed and not shared with all other threads/requests.
Right now i assign my CommunityPrincipal object to the HttpContext.User in the HttpModule, but it requires me to do a cast everytime i need to use properties on the CommunityPrincipal object which isnt defined in the IPrincipal interface.
I'd recommend you stay away from coupling your data to the thread itself. You have no control over how asp.net uses threads now or in the future.
The data is very much tied to the request context so it should be defined, live, and die along with the context. That is just the right place to put it, and instantiating the object in an HttpModule is also appropriate.
The cast really shouldn't be much of a problem, but if you want to get away from that I'd highly recommend an extension method for HttpContext for this... this is exactly the kind of situation that extension methods are designed to handle.
Here is how I'd implement it:
Create a static class to put the extension method:
public static class ContextExtensions
{
public static CommunityPrinciple GetCommunityPrinciple(this HttpContext context)
{
if(HttpContext.Current.Items["CommunityPrinciple"] != null)
{
return HttpContext.Current.Items["CommunityPrinciple"] as CommunityPrinciple;
}
}
}
In your HttpModule just put the principal into the context items collection like:
HttpContext.Current.Items.Add("CommunityPrincipal", MyCommunityPrincipal);
This keeps the regular context's user property in the natural state so that 3rd party code, framework code, and anything else you write isn't at risk from you having tampered with the normal IPrincipal stroed there. The instance exists only during the user's request for which it is valid. And best of all, the method is available to code as if it were just any regular HttpContext member.... and no cast needed.
Assigning your custom principal to Context.User is correct. Hopefully you're doing it in Application_AuthenticateRequest.
Coming to your question, do you only access the user object from ASPX pages? If so you could implement a custom base page that contains the cast for you.
public class CommunityBasePage : Page
{
new CommunityPrincipal User
{
get { return base.User as CommunityPrincipal; }
}
}
Then make your pages inherit from CommunityBasePage and you'll be able to get to all your properties from this.User.
Since you already storing the object in the HttpContext.User property all you really need to acheive you goal is a Static method that acheives your goal:-
public static class MySpecialContext
{
public static CommunityPrinciple Community
{
get
{
return (CommunityPrinciple)HttpContext.Current.User;
}
}
}
Now you can get the CommunityPrinciple as:-
var x = MySpecialContext.Community;
However it seems a lot of effort to got to avoid:-
var x = (CommunityPrinciple)Context.User;
An alternative would be an Extension method on HttpContext:-
public static class HttpContextExtensions
{
public static CommunityPrinciple GetCommunity(this HttpContext o)
{
return (CommunityPrinciple)o.User;
}
}
The use it:-
var x = Context.GetCommunity();
That's quite tidy but will require you to remember to include the namespace where the extensions class is defined in the using list in each file the needs it.
Edit:
Lets assume for the moment that you have some really good reason why even a cast performed inside called code as above is still unacceptable (BTW, I'd be really interested to understand what circumstance leads you to this conclusion).
Yet another alternative is a ThreadStatic field:-
public class MyModule : IHttpModule
{
[ThreadStatic]
private static CommunityPrinciple _threadCommunity;
public static CommunityPrinciple Community
{
get
{
return _threadCommunity;
}
}
// Place here your original module code but instead of (or as well as) assigning
// the Context.User store in _threadCommunity.
// Also at the appropriate point in the request lifecyle null the _threadCommunity
}
A field decorated with [ThreadStatic] will have one instance of storage per thread. Hence multiple threads can modify and read _threadCommunity but each will operate on their specific instance of the field.