[英]Using Unity, How do I autoregister a generic class with a generic interface without registering EVERY type to it
I am using Unity and Unity.AutoRegistration . 我正在使用Unity和Unity.AutoRegistration 。 This line for Unity: Unity的这一行:
unityContainer.RegisterType(typeof(IAction<>), typeof(Action<>));
effectively registers every class in the project to IAction/Action: 有效地将项目中的每个类注册到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 only want specific objects to be registered. 但是,我只想要注册特定的对象。 How would I do that? 我该怎么办? My guess is to add a custom attribute decorator to the specific classes. 我的猜测是为特定的类添加一个自定义属性装饰器。
[ActionAtribute]
public class ObjectB
{ [...] }
And try to use Unity.AutoRegistration . 并尝试使用Unity.AutoRegistration 。 This is where I am stuck at: 这是我被困在的地方:
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();
Include method has overload that allows you to pass lambda to register your type. Include方法具有重载,允许您传递lambda以注册您的类型。 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();
Also, first argument of Include method is Predicate, so if you don't want to use attributes but some other mechanism to define what types to include or exclude, you can do like this: 此外,Include方法的第一个参数是Predicate,因此如果您不想使用属性而是使用其他机制来定义要包含或排除的类型,您可以这样做:
// 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.