Spring.Net IoC and Magic Strings

旧时模样 提交于 2020-01-13 19:48:47

问题


I've been thinking about the IApplicationContext.GetObject(string name) method and it seems to rely fairly heavily on magic strings to get objects from the application context. With other containers like StructureMap you can use generics to specify the configuration and request objects but is there a better way than using strings with the Spring.Net IoC container to request objects from the ApplicationContext?


回答1:


You could have a wrapper that you call, taking a generic type parameter.

Something like this:

public void MyMethod()
{
    IMyService myService = ApplicationContextWrapper.Resolve<IMyService>();
}


public static class ApplicationContextWrapper
{
    public static T Resolve<T>()
    {
        return ApplicationContext.Resolve<T>(typeof(T).Name);
    }
}

Not as good as some of the other IoC contatiners, but at least you will get some kind of compiler support.




回答2:


Spring supports the CommonServiceLocator via an adapter. This interface has the API you expected and you also compile against the common service locator so you can switch IoC containers if you want to without having to modify existing code.



来源:https://stackoverflow.com/questions/1107638/spring-net-ioc-and-magic-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!