Unity 容器 - 解析始终具有相同构造函数参数的对象

Unity container - resolve object which always same constructor parameter

我想在我的代码中只有一个 TestClass 实例。这个 class 需要字符串参数。问题是,如何在 UnityConfig class 中使用字符串参数将此对象注册到统一容器中,然后在代码中到处解析此对象?我这样试过,但在解决过程中出现异常。

这是我的 class:

    public class TestClass
    {
        public TestClass(string str)
        {
            message = str;
        }

        private string message;

        public string Message
        {
            get => message;
            set
            {
                message = value;
            }
        }
    }

这是我的 UnityConfig class:

    public class UnityConfig
    {
        private readonly UnityContainer unityContainer;

        public UnityConfig()
        {
            unityContainer = new UnityContainer();
            unityContainer.RegisterType<TestClass>(new InjectionConstructor("Injected string"));
            var unityServiceLocator = new UnityServiceLocator(unityContainer);
            ServiceLocator.SetLocatorProvider(() => unityServiceLocator);
        }
    }

我是这样解决的:

var serviceLocator = (UnityServiceLocator)ServiceLocator.Current;
var unityContainer = (UnityContainer)serviceLocator.GetService(typeof(UnityContainer));
var testClass = unityContainer.Resolve<TestClass>();

然后我得到这个异常:

Unhandled Exception:

Microsoft.Practices.Unity.ResolutionFailedException: Resolution of the dependency failed, type = "SpotFinder.ViewModels.TestClass", name = "(none)".

Exception occurred while: while resolving.

Exception is: InvalidOperationException - The type String cannot be constructed. You must configure the container to supply this value.


At the time of the exception, the container was:

Resolving SpotFinder.ViewModels.TestClass,(none)
Resolving parameter "str" of constructor SpotFinder.ViewModels.TestClass(System.String str)
Resolving System.String,(none)

我也试过这样注册:

unityContainer.RegisterType<TestClass>(new InjectionConstructor(
                new InjectionParameter("Injected string"))
            );

您使用没有 TestClass 注册的 GetService(typeof(UnityContainer)) 获得 UnityContainer 的新实例,因此它在解析期间给您一个异常。直接使用 serviceLocator 来解析 TestClass 即可。它看起来像这样:

var serviceLocator = (UnityServiceLocator)ServiceLocator.Current;
var testClass = serviceLocator.GetService(typeof(TestClass));

及报名:

var unityContainer = new UnityContainer();
// Configure only one instance of testclass
unityContainer.RegisterType<TestClass>(new ContainerControlledLifetimeManager(), new InjectionConstructor("Injected string"));
var unityServiceLocator = new UnityServiceLocator(unityContainer);
ServiceLocator.SetLocatorProvider(() => unityServiceLocator);

P.S。我不建议你用ServiceLocator,你可以看看他的advantages/disadvantages