Using Unity, how can I authorize a common class with a common interface without registering type EVERY

I use Unity and Unity.AutoRegistration . This line is for Unity:

unityContainer.RegisterType(typeof(IAction<>), typeof(Action<>)); 

Effectively registers each project class in IAction / Action:

 unityContainer.RegisterType<IAction<ObjectA>, Action<ObjectA>>(); unityContainer.RegisterType<IAction<ObjectB>, Action<ObjectB>>(); unityContainer.RegisterType<IAction<ObjectC>, Action<ObjectC>>(); [...] unityContainer.RegisterType<IAction<UnrelatedObject>, Action<UnrelatedObject>>(); [...] 

But I want certain objects to be registered. How can I do it? I suppose adding a special attribute decorator to certain classes.

 [ActionAtribute] public class ObjectB { [...] } 

And try using Unity.AutoRegistration . This is where I am stuck:

 unityContainer.ConfigureAutoRegistration() .Include(If.DecoratedWith<ActionAtribute>, Then.Register() .As ?? // I'm guessing this is where I specify .With ?? // IAction<match> goes to Action<match> ) .ApplyAutoRegistration(); 
+6
generics ioc-container unity-container
source share
1 answer

The Include method has an overload that allows you to pass a lambda to register your type. To achieve exactly what you want with attributes, you can do like this:

  unityContainer.ConfigureAutoRegistration() .Include(If.DecoratedWith<ActionAtribute>, (t, c) => c.RegisterType(typeof(IAction<>).MakeGenericType(t), typeof(Action<>).MakeGenericType(t))) .IncludeAllLoadedAssemblies() .ApplyAutoRegistration(); 

In addition, the first argument to the Include method is Predicate, so if you don't want to use attributes, but some other mechanism to determine which types to include or exclude, you can do this:

  // You may be getting these types from your config or from somewhere else var allowedActions = new[] {typeof(ObjectB)}; unityContainer.ConfigureAutoRegistration() .Include(t => allowedActions.Contains(t), (t, c) => c.RegisterType(typeof(IAction<>).MakeGenericType(t), typeof(Action<>).MakeGenericType(t))) .IncludeAllLoadedAssemblies() .ApplyAutoRegistration(); 
+6
source share

All Articles