依赖注入到类注释中
我正在尝试弄清楚如何执行以下操作:
[CustomAnnotation(thisVariableShouldBeInjected)]
public class MyClass
{
// Normal class stuff
}
现在数据注释正在装饰一个 WCF 服务类,该类本身正在进行构造函数注入。理想情况下,我想使用 Ninject IOC 容器注入带有值的注释,但是这个问题与容器无关。
我刚刚从静态类重构了 Annotation 类,但我不想将其转换回来。
我很高兴进行属性注入(构造函数注入不适用于数据注释,因为它们必须是常量表达式)。我只是不知道在这种情况下该怎么做。
任何建议都非常欢迎!
回应问题/评论:
在此特定实例中,WCF 服务使用属性进行注释,其中一些属性执行审核服务请求和统计信息收集等功能。在这些实例中,注释类由 WCF 基础结构直接调用,我无法在构造函数阶段访问它们。
我正在尝试基于反射的属性注入(如建议的那样)。在这种情况下,注释类是全局的这一事实实际上对我有帮助,因为我正在尝试注入存储库实例 - 无论如何我只需要一个。
这可能就是我最终进行注射的方式。然而,在我的书中,它比静态类及其对存储库的静态引用要好得多。
I'm trying to work out how to do the following:
[CustomAnnotation(thisVariableShouldBeInjected)]
public class MyClass
{
// Normal class stuff
}
Now the data annotation is decorating a WCF service class, which itself has constructor injection going on. Ideally I'd like to inject the annotation with a value using the Ninject IOC container, however this question is container agnostic.
I just refactored the Annotation class from a static class and I'd hate to have to convert it back.
I'm happy to do property injection, (constructor injection isn't going to work with data annotations as they have to be constant expressions afaik). I just don't know how in this instance.
Any suggestions gladly welcomed!
In response to questions/comments:
In this particular instance, the WCF service is annotated with attributes, some of which perform functionality such as auditing service requests and statistics gathering. In these instances the Annotation classes are invoked directly by the WCF infrastructure and I cannot get access to them in the constructor phase.
I'm trying out reflection based property injection (as suggested). In this exact situation the fact that the annotation classes are global actually helps me, as I am attempting to inject repository instances - I only ever needed one anyway.
This may have to be the way I end up doing the injection. However it is much better in my book than the static classes with their static references to the repository.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于属性是类上的编译时元数据,因此您无法在运行时向它们注入会影响特定实例的值。
您可以使用反射在运行时更改属性的值(属性),但它将是全局的,而不是针对任何特定实例。
As attributes are compile time meta data on a class you cannot inject a value into them at runtime that would affect a particular instance.
You can use reflection to change a value (property) of an attribute at runtime but it would be global and not for any particular instance.