# Avoiding using strings when using Spring.Net by incorporating instantiation in class

Totally new to MVP and Spring, and I have what seems to be typical MVP application that uses Spring, where the presenter is instantiated like:

IApplicationContext ctx = ContextRegistry.GetContext();
presenter = (clsPresenter)ctx.GetObject("clsPresenter");


I hate using strings to call code, really, I hate it. So I'm thinking of putting something like

static private readonly string _clsName = typeof(ClsPresenter).Name.ToCamelCase();
public static ClsPresenter getNewPresenterFromSpring()
{
IApplicationContext ctx = ContextRegistry.GetContext();
return (ClsPresenter)ctx.GetObject(_clsName);
}


into all of the presenters. So that instead of the the two lines above which use a string to find the presenter, it would be one line using the static method:

presenter = ClsPresenter.getNewPresenterFromSpring();


I know this violates the SRP, and it might look to be introducing some coupling between the Presenter classes and Spring, but it seems to me that it's not really coupled any more than it was before, it's just now type (and typo) safe, while living in a somewhat weird place. If I stop using Spring, I simply replace this call with whatever else gets used instead.

Am I missing something that makes this a really bad idea? Is there a better way of avoiding the usage of strings? Should I just suck it and make sure I don't spell "clsPresenter" as "classPresenter"?

• Isn't Spring for Java? Or do you mean Spring.Net? Or something else? Sep 13, 2012 at 9:11
• I meant Spring.Net Sep 13, 2012 at 14:32

1. Not sure if that is just the case in your example but it's rather uncommon in C# to prefix classes with cls or class. In fact the only commonly used type identifier as part of the type name is usually the I prefix for interfaces.

2. Method names in C# are usually PascalCase naming convention. camelCase is used for local variables.

3. Not entirely sure about the whole structure of your code but to me it looks like you should be able to easily move the code into a separate helper class like this:

public static class SpringHelper
{
public static T GetNewPresenter<T>()
{
IApplicationContext ctx = ContextRegistry.GetContext();
return (T)ctx.GetObject(typeof(T).Name.ToCamelCase());
}
}


You would call it like this then:

SpringHelper.GetNewPresenter<ClsPresenter>();


If all your presenters have a base class your could also add a where clause to restrict the types.

This would at least remove the dependency out of the presenter class.