简体   繁体   中英

Unity InjectionFactory Doesn't Run

Summary: It seems like the InjectionFactory is not being run for a type mapping. I'd like to know why and how to solve the problem.

At first, I tried to register the interface

Container.RegisterType<ILogger>(new InjectionFactory((c, t, n) => {
                return LogManager.GetLogger(n);
            }));

And resolve using the service locator

ServiceLocator.GetInstance<ILogger>("Operation Manager");

This resulted in

The current type, NLog.ILogger, is an interface and cannot be constructed. Are you missing a type mapping?

After some tinkering, I decided to try a different approach and registered the service using the concrete type instead

Container.RegisterType<Logger>(new InjectionFactory((c, t, n) => {
                    return LogManager.GetLogger(n);
                }));

And changed the resolution method to

public OperationService([Dependency("Operation Service")]Logger logger)

This results in the following error:

 The type Logger does not have an accessible constructor.

The only reason I can think of for this behavior is if the function I've passed via the InjectionFactory isn't actually being called to resolve the object.

This is because you registered the type without a name, and you're trying to resolve it by name. Unity looks for a registration for (ILogger, "Operation Manager") , but it can't find any. Your registration with no name is never considered an eligible candidate, so the InjectionFactory is not called.

As far as I know, there's no built-in way to achieve what you're trying to do. It might be possible with a custom extension, but my attempts so far have been unsuccessful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM