I have done all my mapping use static classes and extention methods, which keeps my controller codes clean it makes things easier to manage, I didn’t like Automapper.
However in the mapping I need to access database content to populate things, so at the top of the classes I have:
private static ISettingService _SettingService = DependencyResolver.Current.GetService<ISettingService>();
Sometime I have a few of these, I have been told this is bad practice, can someone explain why, and whats the way around it?
Typically it is not a good idea to maintain state in a static variable unless you are using singleton pattern. In your example your SettingService object will be shared by all your users. I recommend passing this as an input parameter to you extension method.
If you want to share the same object across all users, then try following the singleton pattern.
Thanks for the info, I am using
builder.Register(c => new MyContext()).As<IUnitOfWork>().SingleInstance();
I have to use SingleInstance becuase I am using IEnumerable and IQueryable in my service layer and repository
My mapping from viewModel to entity and back again is very complex, and if I had to input it as a paramater as the root extension it would be 3 -10 extensions later before it would be used which seems a little silly.
Right as far as I am concerned all users will be using the SettingService anyway, but I am not 100% sure what a singleton pattern is or how to use it effectively, do you have any additional information I can loo at?
Based on your description, it seems what you are doing is good. If possible try to inject the object using the constructor.
I am using static classes and static extenstion methods so I can’t inject into the constructors and where the service layer is needed is 3-4 models into the mapping so would be a massive amount of work and unclean coding to do it like that.
Should my services in the DIConfig also be SingleInstance and not InstancePerHttpRequest?
Yes use singleton.
Thanks for the help, back to work today so I guess I need to read up, does anyone have a link to explain what the difference are and how to use them effectively, in an easy to understand none techie manner?