How do I add a custom formatter in ASP.NET and AutoFac #421
-
Greetings all, I have created a custom formatter and tried to add it in the Startup routine of an ASP.Net application. Unfortunately, it does not seem to be available later when I try to use it. I get an exception that it can't find the formatter. I worked around the problem by calling
In the constructor of the classes where I use it. This works, but seems counter-intuitive. Is this the way it's supposed to work or am I doing something wrong? My thanks :) Morgan Haldane |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 9 replies
-
Yes, this does not work
because the custom extension is registered in a In ASP.NET you could create a new |
Beta Was this translation helpful? Give feedback.
-
Ok, after a bit of research, I got this and it seems to work: In my ApplicationModule class (where I do all my dependency injection registrations) i have this in the Load method: builder.Register(c =>
{
SmartFormatter formatter = new SmartFormatter()
.AddExtensions(
new StringSource(),
// will automatically be added to the IFormatter list, too
new ListFormatter(),
new DictionarySource(),
new ValueTupleSource(),
new ReflectionSource(),
// for string.Format behavior
new DefaultSource(),
new KeyValuePairSource())
.AddExtensions(
new PluralLocalizationFormatter(),
new ConditionalFormatter(),
new IsMatchFormatter(),
new NullFormatter(),
new ChooseFormatter(),
new SubStringFormatter(),
// for string.Format behavior
new DefaultFormatter());
IFormatter numberFormatter = c.ResolveNamed<IFormatter>("nbrFormatter");
formatter.AddExtensions(numberFormatter);
return formatter;
}).AsSelf().InstancePerDependency(); In the places where I need formatting, I have this: private readonly SmartFormatter formatter;
public class WorkerClass
{
// Other constructor stuff here...
formatter = factory.Create<SmartFormatter>(); // factory is my factory class used to create objects. It uses AutoFac internally.
}
public void WorkerMethod()
{
int someValue;
// method does stuff
string stuff = formatter.Format("{value:nbrFormatter(x)}", new {value = someValue});
DoSomethingWithStuff(stuff);
} Initially, I got an error saying I was missing SourceExtensions. I looked up how the default formatter was initialized and copied that code here. The Wiki didn't have anything that I could find, other than a warning to "for the beginning, leave Thanks, Morgan |
Beta Was this translation helpful? Give feedback.
Ok, after a bit of research, I got this and it seems to work:
In my ApplicationModule class (where I do all my dependency injection registrations) i have this in the Load method: