Global constants in separate file. Is it a good idea? - asp.net-mvc

I'm currently working on ASP.NET MVC application. I'm planning to create a static class where I plan to hold all the global string constants like session names.
The reason I'm hesitant is because it's kind of smell but I'm not aware of better alternative.
Please show me the light how to define global constants.

vadim,
i do exactly as you propose and use a static class for this purpose. You then get the advantage of strongly typed accessors PLUS the ability to add overrides (in the form of methods), should you require them.
here's a snippet:
public static class Config
{
private const string NotSet = "**VALUE NOT SET**";
private const int pageSize = 5;
public static string CustomCache
{
get
{
return ConfigurationManager.AppSettings["CustomCache"] ?? NotSet;
}
}
public static int PageSize
{
get
{
// simple default - no setter
return pageSize;
}
}
}
typical usage:
items = _repository.GetPaged(pageNumber, Config.PageSize)
in the above class, some settings are called '2nd generation' from the app settings in the web.config but with strong typing in the classes to ensure runtime error checking etc.. others are purely static settings defined in the class.
it's the flexibility to do all of the above that (in my opinion) gives this approach both appeal and a real strength.

Another alternative would be to create a resources (.resx) file. Or if these are configurable values, they can go in web.config or a database configuration table.

Whether it is MVC or Web forms, I use a combination of database entries (for site settings that can be modified by dashboard) and web.config appSettings (for site settings that do not change often or at all, i.e. constant).

You can use global.asax file for this purpose - I would use accessors for them e.g.
private static int var ;
public static int VAR
{
get { return var ; }
}

Related

Default values for constructor arguments in a library project

I am writing a library that will provide a collection of public types to its consumers.
I want to make types from this library dependency injection friendly. This means that every class needs to have a constructor through which it is possible to specify every single dependency of the object being initialized. I also want the library to adhere to the convention over configuration principle. This means that if a consumer wants the default behavior, he may use a parameterless constructor and the object will somehow construct the dependencies for itself.
In example (C#):
public class Samurai {
private readonly IWeapon _weapon;
// consumers will use this constructor most of the time
public Samurai() {
_weapon = ??? // get an instance of the default weapon somehow
}
// consumers will use this constructor if they want to explicitly
// configure dependencies for this instance
public Samurai(IWeapon weapon) {
_weapon = weapon;
}
}
My first solution would be to use the service locator pattern.
The code would look like this:
...
public Samurai() {
_weapon = ServiceLocator.Instance.Get<IWeapon>();
}
...
I have a problem with this, though. Service locator has been flagged as an anti-pattern (link) and I completely agree with these arguments. On the other hand, Martin Fowler advocates use of the service locator pattern exactly in this situation (library projects) (link). I want to be careful and eliminate the possible necessity to rewrite the library after it shows up that service locator really was a bad idea.
So in conclusion - do you think that service locator is fine in this scenario? Should I solve my problem in a completely different way? Any thought is welcome...
If you want to make life easier for users who are not using a DI container, you can provide default instances via a dedicated Defaults class which has methods like this:
public virtual Samurai CreateDefaultSamurai()
{
return new Samurai(CreateDefaultWeapon());
}
public virtual IWeapon CreateDefaultWeapon()
{
return new Shuriken();
}
This way you don't need to pollute the classes themselves with default constructors, and your users aren't at risk of using those default constructors unintentionally.
There is an alternative, that is injecting a specific provider, let's say a WeaponProvider in your case into your class so it can do the lookup for you:
public interface IWeaponProvider
{
IWeapon GetWeapon();
}
public class Samurai
{
private readonly IWeapon _weapon;
public Samurai(IWeaponProvider provider)
{
_weapon = provider.GetWeapon();
}
}
Now you can provide a local default provider for a weapon:
public class DefaultWeaponProvider : IWeaponProvider
{
public IWeapon GetWeapon()
{
return new Sword();
}
}
And since this is a local default (as opposed to one from a different assembly, so it's not a "bastard injection"), you can use it as part of your Samurai class as well:
public class Samurai
{
private readonly IWeapon _weapon;
public Samurai() : this(new DefaultWeaponProvider())
{
}
public Samurai(IWeaponProvider provider)
{
_weapon = provider.GetWeapon();
}
}
I have used the following approach in my C# project. The goal was to achieve dependency injection (for unit / mock testing) whilst not crippling the implementation of the code for a "normal use case" (i.e. having a large amount of new()'s that are cascaded through the execution flow).
public sealed class QueueProcessor : IQueueProcessor
{
private IVbfInventory vbfInventory;
private IVbfRetryList vbfRetryList;
public QueueProcessor(IVbfInventory vbfInventory = null, IVbfRetryList vbfRetryList = null)
{
this.vbfInventory = vbfInventory ?? new VbfInventory();
this.vbfRetryList = vbfRetryList ?? new VbfRetryList();
}
}
This allows DI but also means any consumer doesn't have to worry about what the "default instance flow" should be.

Get physical of the root of the website from inside a class?

Hi,
I have a mailhandler class in my MVC webapplication and needs to get a physical path to the mailTemplate file (a couple of folders down the root). How do I do this? Do I have to send in some kind of httpContext? My mailHandler is a singelton so there is no constructor for parameters :
public static EmailHandler Instance
{
get {
if (EmailHandler._emailHandler == null)
EmailHandler._emailHandler = new EmailHandler();
return EmailHandler._emailHandler; }
set { EmailHandler._emailHandler = value; }
}
Any idea?
Personally, I would just tell it the base-path to use; then the same code can work in a number of environments, not just web. If you are web-bound, HttpContext.Current may help. If you want to pass it in, I would instead pass in the abstracted HttpContextBase, ala MVC.
But passing in a string of the base-path is a lot easier :)
you can store physical address of base folder in config file. Then do Path.Combine(baseFolder,templatefile) to get full path. This is preferred way, since it does not depend on having httpcontext accessible.
you can map that folder as virtual folder in IIS and then get physical path using Server.MapPath function
You could always abstract your application configuration :)
public interface IApplicationConfiguration
{
string EMailTemplateFolder { get; }
}
Then pass in an instance of a class implementing this interface into the relevant method. Passing in the instance to your EMailHandler is another option:
YourClassEMailHandlerContainer.Instance
.InitializeWith(new ApplicationConfiguration())
Where ApplicationConfiguration : IApplicationConfiguration.
After this you just call your method.
YourClassEMailHandlerContainer.Instance.ParseTemplate(name)
Where internally:
var templateFile =
Path.Combine(applicationConfiguration.EMailTemplateFolder, name);
Hope that makes sense.

Blackberry Application design question - Singletons

I'm refactoring a Blackberry application and I have a scenario where I think I'm currently using a global variable, but I'm not sure if that's the right thing to do. Briefly, my scenario is the following -
My app first requires the user to login. The (uid, pass) are sent to a web service which determines if the login is valid and returns some additional data. I have a model object on my application that looks something like this - (After a succesfully calling login)
class UserDataModel
{
private String username;
private String password;
private String fullName;
private String age;
...
/* Getters and Setters */
}
I also have a UserPreferencesModel which contains all the preferences that the user has saved. (I need to back them up to our database / restore them across devices etc.)
Additionally, in what context are Globals generally used in the context of mobile development?
Thanks,
Teja.
Well, I made a simple example how you can to use the RuntimeStore, I hope that this be of helpful
public class myData
{
long ID = 0xf46f5a7867d69ff0L;
String d1;
RuntimeStore runTS = RuntimeStore.getRuntimeStore();
public void setData(String _d1)
{
try
{
syncronized (runTS)
{
runTS.put(ID, _d1);
}
}catch(Exception ex){}
}
public String getData()
{
String s;
try
{
s = (String)(RuntimeStore.getRuntimeStore().get(ID));
}catch(Exception ex){}
return s;
}
}
There is nothing particularly special about BlackBerry in regards to using singletons. Of course, true constants should be just statics. And all of them should be final but Strings: there is a memory usage penalty if a static final String is reused often in your code.
What singleton gives you is the ability to replace or remove complex models with relatively long lifetime via a single point of control.
In your example, DataModel is a good candidate. BlackBerry is a personal device, so there is a big chance this DataModel with user profile and, probably, additional data, will survive for the lifetime of the active application.
So,
class UserDataModel
{
private static UserDataModel singleton;
public static void login() {
//get credentials
//authenticate
singleton = new UserDataModel(... user profile data...);
}
public static UserDataModel getInstance() { return singleton; }
private String username;
private String password;
private String fullName;
private String age;
...
/* Getters and Setters */
}
This way of doing it is a valid, a little simplified, example. If something changes (say, server host), all you need to do is to replace singleton. Also, it opens up a possibility to use polymorphism, if UserDataModel implementation is different for different servers, etc. There are many benefits to it at the cost of one extra variable in a chain of accessors. Again, there is nothing special about BlackBerry here, this reasoning is valid in any Java application.
Why the example is simplified is because you need to think about threads. If there is even a remote chance that something somewhere will access getInstance() on a different thread than login(), you have to properly synchronize them (even though I was never able to break a simple object reference by accessing/updating it from different threads on BlackBerry).
their are some scenarios when having static variable is good idea. like for Constant String fields.
here is the link to blackberry official Best practice document for writing efficient code for blackberry platform.
Black Berry: Best Practices: writing efficient code

Dependency injection - need larger example?

i'm looking for a larger example of dependency injection and how it can be implemented. If class A depends on class B and passes a reference of class C to B's constructor, must not class A also take a reference to class C in it's constructor? This means that the main method in the application should create all classes really, which sounds wierd?
I understand that using DI frameworks we can have it in XML files somehow, but that sounds like it could be hard to quickly see what type that really is instanciated? Especially if it a very large application.
You are correct and each DI framework has a different way of managing it.
Some use attributes on the properties etc to denote dependency and then "automagically" supply an instance of the correct type, while others (say castle windsor for .net) allow xml configuration, fluent or other methods for "wiring up" the dependency graph.
Also no, class A takes a built reference to an instance of B which was built using an instance of C. A needs to know nothing about C unless exposed via B.
public class C { }
public class B { public B(C c) { ... }}
public class A { public A(B b) { ... }}
// manual wireup
C c = new C();
B b = new B(c);
A a = new A(b);
// DI framework
InversionOfControlContainer container = new InversionOfControlContainer(... some configuration);
A a = container.ResolveInstanceOf<A>();
// container dynamically resolves the dependencies of A.
// it doesnt matter if the dependency chain on A is 100 classes long or 3.
// you need an instance of A and it will give you one.
Hope that helps.
to answer your question about classes A,B,and C, A only needs a reference to B.
Most DI frameworks do not require you to use XML for configuration. In fact, many people prefer not to use it. You can explicitly set things up in code, or use some kind of conventions or attributes for the container to infer what objects should fulfil dependencies.
Most DI frameworks have a facility for "lazy loading" to avoid the creation of every single class up front. Or you could inject your own "factory or builder" objects to create things closer to the time when they will be used
You've not said what language you are using. My example below is in C# using the Unity container. (obviously normally you would use interfaces rather than concrete types):
container = new UnityContainer();
container.RegisterType<C>();
container.RegisterType<B>();
A a = container.Resolve<A>();
here's a few examples from the PHP Language, hope this helps you understand
class Users
{
var $Database;
public function __construct(Database $DB)
{
$this->Database = $DB;
}
}
$Database = Database::getInstance();
$Users = new Users($Database);
From this example the new keyword is used in the method getInstance(), you can also do
$Users = new Users(Database::getInstance());
Or another way to tackle this is
class Users
{
/*Dependencies*/
private $database,$fileWriter;
public function addDependency($Name,$Object)
{
$this->$Name = $Object;
return $this;
}
}
$Users = new Users();
$Users->addDependency('database',new Database)->addDependency('fileWriter',new FileWriter);
Update:
to be honest, I never use Dependency Injection as all its doing is passing objects into classes to create a local scope.
I tend to create a global entity, and store objects within that so there only ever stored in 1 variable.
Let me show you a small example:
abstract class Registry
{
static $objects = array();
public function get($name)
{
return isset(self::$objects[$name]) ? self::$objects[$name] : null;
}
public function set($name,$object)
{
self::$objects[$name] = $object;
}
}
Ok the beauty of this type of class is
its very lightweight
it has a global scope
you can store anything such as resources
When your system loads up and your including and initializing all your objects you can just store them in here like so:
Registry::add('Database',new Database());
Registry::add('Reporter',new Reporter());
Where ever you are within your runtime you can just use this like a global variable:
class Users
{
public function getUserById($id)
{
$query = "SELECT * FROM users WHERE user_id = :id";
$resource = Registry::get("Database")->prepare($query);
$resource->bindParam(':id',$id,PDO::PARAM_INT);
if($resource->execute())
{
//etc
}else
{
Registry::get('Reporter')->Add("Unable to select getUserById");
}
}
}
i see this way of object passing is much cleaner
If anybody is still looking for a good example which shows DI without IoC Containers (poor man's DI) and also with IoC Container (Unity in this example) and registering the types in code and also in XML you can check this out: https://dannyvanderkraan.wordpress.com/2015/06/15/real-world-example-of-dependeny-injection/

Ninject 2.0: Property Injection without attribute

Is there a way to use Property Injection in Ninject 2 without using the [Inject] attribute? This creates a dependency to Ninject in the class that will be wired using it and I prefer to avoid having unneeded dependencies to my IoC container, that's why I end up using Constructor Injection more often.
I guess the same applies to Method Injection
I followed Ruben's tip and posted a small blog post on how to achieve this, but here's the quick answer:
Create a custom attribute:
public class InjectHereAttribute : Attribute
{
}
The target class will now look like this:
public class Samurai
{
[InjectHere]
public IWeapon Context { get; set; }
}
Now Ninject must be configured to use the custom attribute, this can be done by creating an implementation of IInjectionHeuristic that recognizes the custom attribute:
public class CustomInjectionHeuristic : NinjectComponent, IInjectionHeuristic, INinjectComponent, IDisposable
{
public new bool ShouldInject(MemberInfo member)
{
return member.IsDefined(
typeof(InjectHereAttribute),
true);
}
}
And finally add this behavior to the Ninject Kernel using the Components collection, it will run along the existing components, namely the default implementation of IInjectionHeuristic, which means either the default or the custom attribute can be used.
// Add custom inject heuristic
kernel.Components.Add<IInjectionHeuristic, CustomInjectionHeuristic>();
You can pass in another [attribute] type to the Kernel upon creation which can be used instead of InjectAttribute, but you'll still have to reference something centrally OOTB.
There was a similar question very recently about doing PI without attributes - there's no OOTB (as in directly on the fluent configuration interface) to put in a custom scanner but the extensibility points (you add a component that implements a Ninject interface as you build your Kernel that dictates how that aspect is to be work if looking for a given attribute isnt't what you want) are in there to determine where to inject based on Convention over Configuration - there's nothing stopping you amending the scanning to be based on just an attribute name (so it doesnt necessarily have to live in a central location).
Note that, in general, constructor injection is good for lots of reasons anyway, including this one, and keeping you code container agnostic is important (even if you're currently happy with one!)
I was able to accomplish this using a Heuristic class:
public sealed class MyInjectionHeuristic : NinjectComponent, IInjectionHeuristic
{
private static readonly IList<Type>
_propertyInjectible =
new List<Type>
{
typeof(IMyService),
};
/// <summary>
/// Returns a value indicating whether the specified member should be injected.
/// </summary>
/// <param name="member">The member in question.</param>
/// <returns><c>True</c> if the member should be injected; otherwise <c>false</c>.</returns>
public bool ShouldInject(MemberInfo member)
{
var info = member as PropertyInfo;
if( member == null || info == null )
return false;
if (info.CanWrite)
return _propertyInjectible.Contains(info.PropertyType);
if( this.Settings == null )
return false;
var propList = member.GetCustomAttributes(this.Settings.InjectAttribute, true);
return propList.Length > 0;
}
}
When creating your kernel:
var heuristics = _kernel.Components.Get<ISelector>().InjectionHeuristics;
heuristics.Add(new MyInjectionHeuristic());
Simple add additional types to the IList when you want to inject other types via properties.

Resources