c# - How to get the instance into which the activated object has been injected at activation time? -
i'm trying utilize ninject
me build possible tree of service classes. i'd inject ilogger
instance using incallscope
child service class use same logger.
the logger implementation has property called rootservice
, point upper-most service class instance uses logger. use information when categorizing logged events according service class has come (child classes not define "log scope", hence use incallscope
).
can fine-tune ilogger
ninject binding have kind of callback when ilogger
instance activated, , had there instance too, got injected? there set rootservice
property of logger.
there's onactivation
binding extension callback executed when ilogger
instanciated. can following:
public class test { [fact] public void foo() { var kernel = new standardkernel(); kernel.bind<service>().toself(); kernel.bind<logger>().toself() .onactivation((ctx, logger) => logger.initalize(ctx.request.target.member.declaringtype)); var service = kernel.get<service>(); service.logger.rootservice.should().be(typeof(service)); } } public class logger { public type rootservice { get; private set; } public void initalize(type rootservice) { this.rootservice = rootservice; } } public class service { public logger logger { get; private set; } public service(logger logger) { logger = logger; } }
however, icontext
not provide access "parent" instance, can access type it's injected into, not instance.
also, if should enough, there's no need use onactivation
extension, should able this:
public class test { [fact] public void foo() { var kernel = new standardkernel(); kernel.bind<service>().toself(); kernel.bind<logger>().toself() .withconstructorargument( typeof(type), ctx => ctx.request.target.member.declaringtype); var service = kernel.get<service>(); service.logger.rootservice.should().be(typeof(service)); } } public class logger { private readonly type _rootservice; public logger(type rootservice) { _rootservice = rootservice; } public type rootservice { { return _rootservice; } } } public class service { public logger logger { get; private set; } public service(logger logger) { logger = logger; } }
Comments
Post a Comment