Include方法具有重载,允许您传递lambda以注册类型。要使用属性实现您想要的效果,可以执行以下操作:
unityContainer.ConfigureAutoRegistration()
.Include(If.DecoratedWith<ActionAtribute>,
(t, c) => c.RegisterType(typeof(IAction<>).MakeGenericType(t), typeof(Action<>).MakeGenericType(t)))
.IncludeAllLoadedAssemblies()
.ApplyAutoRegistration();
另外,Include方法的第一个参数是谓词,所以如果您不想使用属性而是其他机制来定义要包含或排除的类型,可以这样做:
// 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();