Singleton in use in authentication - c#

I came across a Singleton implementation in a site I was tasked to make changes to. The only thing I know about Singleton is its definition and as such never had an opportunity to work "with" it. So I started to read articles and this one on Implementing the Singleton Pattern in C# nicely explains it. Except that the code I have looks not quite the same. Can some take a look at this and points out what this code does or how is it different?
public class Singleton<TSingleton> where TSingleton : class, new()
{
private static readonly Lazy<TSingleton> instance = new Lazy<TSingleton>(() => new TSingleton());
public static TSingleton Instance { get { return instance.Value; } }
}
This class is called like this Singleton<AccessLogger>.Instance.LogAccess(accessData); where accessData is an instance of AccessLoggerData and basically contains environment, page and user information. The accessData is an instance of AccessLoggerData class:
public class AccessLoggerData
{
public string Environment = Singleton<ApplicationSettings>.Instance.Environment;
public string Page, UserId;
public AccessLoggerData(string page, string user)
{
this.Page = page;
this.UserId = user;
}
}
Strangely as I'm writing this post and somehow it is becoming more clear as to how these pieces come together, but one thing remains unclear, why would it be necessary to allow only one instance of this accessData object?

This looks like a generic implementation of the singleton pattern using the (newish) Lazy keyword. In its default form it make sure that only a single instance of the object created is accessed (LazyThreadSafetyMode.ExecutionAndPublication). This is important as the initialization code of the object being created might have some side effects that would be undesirable if executed twice. Checkout http://csharpindepth.com/articles/general/singleton.aspx for some more information on this.

"why would it be necessary to allow only one instance of this accessData object?"
It's a little hard to say exactly just based on the code provided. Perhaps multiple users are active on the system at the same time. The class name AccessLoggerData suggests that info is being logged.
You'd only want one instance logging that data if it involves file access. You wouldn't want multiple instances competing for a file write lock. The problem with this is there's nothing to suggest that in the actual code. Maybe it's meant to allow one user at a time and their state is held by this Singleton. In that case, it's bad design. Considering there's another Singleton within AccessLoggerData for application settings, you have a Singleton as a global: not good. It may be Singletonitis by the former developer.

Related

Is it good design to have state-representative properties on a service class?

I have an application with a service class that retrieves database metadata from a database and returns it to calling classes.
To connect to the database, the service class methods accept a parameter that details the connection credentials.
I'm considering a change whereby the credentials would be stored within the service class. One of the reasons for this is that calling classes (which have the responsibility, for example, of comparing schemas on different servers) may connect to multiple different databases/servers, so the calling class would basically have a collection of these service classes, rather than a collection of connection credentials (e.g., IConnectionInfo in the following example).
Another thing I might like to do within the application is to have implementation of this service class (IDatabaseService in the following example) for different types of RDBMS (e.g., SQL Server, Oracle, etc.), and this seems like the best way of leaving it open to that (the information returned from the service would be very generic and applicable to all supported types of RDBMS).
Example code for what the service class might look like:
public class DatabaseService : IDatabaseService
{
private readonly IConnectionInfo ConnectionInfo;
public bool IsConnected; // INotifyPropertyChanged
public string ServerName => IConnectionInfo.ServerName;
public string DatabaseName => IConnectionInfo.DatabaseName;
public DatabaseService(IConnectionInfo connectionInfo)
{
ConnectionInfo = connectionInfo;
}
public IEnumerable<Table> GetTables()
{
...
}
public IEnumerable<Column> GetTableColumns(Table table)
{
...
}
}
There are a few reasons I'm a bit doubtful of this approach:
I'm implementing INotifyPropertyChanged within this class so that I can update the UI to show the user whether or not they are connected (e.g., I could switch this to false if any calls to the server failed). For this reason it seems to behave like a ViewModel (as opposed to a Service).
I'm unsure as to whether it's good practice to have properties on a service class that represent its state, e.g., ConnectionInfo, IsConnected.
Does the above look like an acceptable design?
Update: Further Thoughts and Explanation
I suppose the specific programming problem I'm trying to solve is that, for example, I might have a class for SQL Server credentials, and a class for Oracle credentials, both of which would be IConnectionCredentials. I would then have several corresponding implementations of IDataService, which would accept IConnectionCredentials as an argument. The issue would be that not all implementations of IDataService would work with all implementations of IConnectionCredentials, which seems flawed to me, and so I thought it would make sense to combine the data access layer and the "data accessor" object into one class. I suppose it might be feasible to have IDataService contain logic to determine which version of the "real" data access interface to use. For example:
public class DataService : IDataService
{
private readonly RealDataServiceFactory RealDataServiceFactory;
public IEnumerable<Table> GetTables(IConnectionCredentials connectionCredentials)
{
return RealDataServiceFactory.Create(connectionCredentials).GetTables(connectionCredentials);
}
}
public class RealDataServiceFactory
{
public IRealDataService Create(IConnectionCredentials connectionCredentials)
{
if (connectionCredentials is SqlServerConnectionCredentials)
{
return new SqlServerDataService();
}
else if ...
}
}
Another reason I wanted the IsConnected property in the data access class is because there are other reasons that the service might not return data other than the connection not working, and I didn't feel the logic to determine that belonged in the calling class, and so liked the idea that the data service could simultaneously return null to some call and also state to the application and UI, "there's a problem with my connection". In the above implementation, I would also lose this, though I suppose it could be achieved by the data service marking IsConnected as false on the incoming IConnectionCredentials before returning.
It's ultimately up to you what to do, but it sounds like this design conflates two (or more?) concerns into one:
User interface updates (INotifyPropertyChanged)
Data access
This gives the class more than a single reason to change. In other words, it violates the Single Responsibility Principle (SRP).
Now, no-one says that you must obey the SRP. This, and the other SOLID principles, are guidelines for dealing with certain kinds complexity. If you don't have the problems that SOLID addresses, then you don't have to follow those principles.
In practice, though, it can be hard to predict future problems. A code base is rarely problematic from the outset. It slowly devolves from something simple to something more complicated.
While the proposed design sounds like it has mixed concerns (as opposed to separation of concerns), perhaps it's benign in practice. After all, INotifyPropertyChanged is a base class library interface, so you're aren't introducing coupling to some specific technology. I'd be wary of expanding the scope of UI-related updated on that class, though.

Parameters and Constructors

I've read a lot of detailed things throughout Stack Overflow, Microsoft Developer Network, and a couple of blogs. The general consensus is "A Constructor shouldn't contain large quantities of parameters." So encountering this got me thinking-
Initial Problem: My application contains around fifteen variables that are constantly being used throughout the application. The solution I came up with is I'll create a single class that will inject the values to the Properties.
So this seemed to work quite well, it made my life quite easy as I could pass the object into another class through the Constructor without having to assign all these variables to each method. Except this lead to another issue-
public class ServerParameters
{
// Variable:
private string template;
private string sqlUsername;
private string sqlPassword;
private string sqlDatabase;
private string sqlServer;
public ServerParameter(string _template, string _sqlDatabase, string _sqlServer,
string _sqlUsername, string _sqlPassword)
{
template = _template;
sqlUsername = _sqlUsername;
sqlPassword = _sqlPassword;
sqlDatabase = _sqlDatabase;
sqlServer = _sqlServer;
}
// Link the private strings to a group of Properties.
}
So already this Constructor has become significantly bloated- But now I need to implement even more Parameters.
Problem Two: So I have a bloated Constructor and by implementing other items that don't entirely fit with this particular Class. My solution to this, was to create a subclass or container to hold these different classes but be able to utilize these classes.
You now see the dilemma, which has aroused the all important question- When you can only inherit once, how can you build a container that will hold all of these subclasses?
And why shouldn't you use so many parameters in a Constructor, why is it bad exactly?
My thought on how to implement a Container but I feel like I'm doing it wrong- Because I constantly get Null Reference Exception when I try to use some of these Parameters.
public class VarContainer
{
private ServerParameter server;
private CustomerParameter customer;
public VarContainer(ServerParameter _server, CustomerParameter _customer)
{
server = _server;
customer = _customer;
}
}
I'm assuming it is because the internal class itself isn't actually getting those assigned variables, but I'm completely lost on the best approach to achieve my goal-
The main intent of "don't do work in your constructor" is to avoid side effects where you create an object and it does a significant amount of work that can impact global state unexpectedly or even take a long time to complete which may disrupt the caller's code flow.
In your case, you're just setting up parameter values, so this is not the intention of "don't do work", since this isn't really work. The design of your final container depends on your requirements - if you can accept a variable list of properties that are set on your class (or struct) then perhaps an initializer when you construct the object is more appropriate.
Assuming that you want all of your properties from the get go, and that you want grouping like you called out in the question, I would construct something similar to:
public class Properties
{
public ServerProperties Server { get; private set; }
public CustomerProperties Customer { get; private set; }
public Properties(ServerProperties server, CustomerProperties customer)
{
Server = server;
Customer = customer;
}
}
I'm leaving the implementation of ServerProperties and CustomerProperties to you, but they follow the same implementation pattern.
This is of course a matter of preferences but I always give my constructors all the parameters they need so that my objects has basic functionality. I don't think that 5 parameters is bloated and adding a container to pass parameters adds much more bloat in my opinion than adding a few more parameters. By new bloat I mean that you will probably have a new file for that, with new classes and new imports. Calling code has to write more using directives and link to correct libraries which needs to be exported correctly as well.
Adding a wrapping class for parameter masks the real problem, that your class might be too complicated, it does not solve it and generally aggravates it.
You can have any amount of parameters you want in a constructor. It's just that if you have too many (how many is too much? that's really subjective), it gets harder and harder to make a new instance of that class.
For example, suppose you have a class with 30 members. 27 of them can be null. If you force it to receive a value for each member in the constructor, you'll get code like this:
Foo bar = new Foo(p1, p2, p3, null, null, null, null, null, null /*...snip*/);
Which is boring to write and not very readable, where a three parameter constructor would do.
IMO, this is what you should receive in your constructors:
First, anything that your instance absolutely needs in order to work. Stuff that it needs to make sense. For example, database connection related classes might need connection strings.
After those mentioned above, you may have overloads that receive the stuff that can be most useful. But don't exagerate here.
Everything else, you let whomever is using your code set later, through the set accessor, in properties.
Seems to me like you could use dependency injection container like Unity or Castle Windsor.

should I make this class static?

In the projects I worked on I have classes that query/update database, like this one,
public class CompanyInfoManager
{
public List<string> GetCompanyNames()
{
//Query database and return list of company names
}
}
as I keep creating more and more classes of this sort, I realize that maybe I should make this type of class static. By doing so the obvious benefit is avoid the need to create class instances every time I need to query the database. But since for the static class, there is only one copy of the class, will this result in hundreds of requests contend for only one copy of static class?
Thanks,
I would not make that class static but instead would use dependency injection and pass in needed resources to that class. This way you can create a mock repository (that implements the IRepository interface) to test with. If you make the class static and don't pass in your repository then it is very difficult to test since you can't control what the static class is connecting to.
Note: The code below is a rough example and is only intended to convey the point, not necessarily compile and execute.
public interface IRepository
{
public DataSet ExecuteQuery(string aQuery);
//Other methods to interact with the DB (such as update or insert) are defined here.
}
public class CompanyInfoManager
{
private IRepository theRepository;
public CompanyInfoManager(IRepository aRepository)
{
//A repository is required so that we always know what
//we are talking to.
theRepository = aRepository;
}
public List<string> GetCompanyNames()
{
//Query database and return list of company names
string query = "SELECT * FROM COMPANIES";
DataSet results = theRepository.ExecuteQuery(query);
//Process the results...
return listOfNames;
}
}
To test CompanyInfoManager:
//Class to test CompanyInfoManager
public class MockRepository : IRepository
{
//This method will always return a known value.
public DataSet ExecuteQuery(string aQuery)
{
DataSet returnResults = new DataSet();
//Fill the data set with known values...
return returnResults;
}
}
//This will always contain known values that you can test.
IList<string> names = new CompanyInfoManager(new MockRepository()).GetCompanyNames();
I didn't want to ramble on about dependency injection. Misko Hevery's blog goes into great detail with a great post to get started.
It depends. Will you ever need to make your program multithreaded? Will you ever need to connect to more than one database? Will you ever need to store state in this class? Do you need to control the lifetime of your connections? Will you need data caching in the future? If you answer yes to any of these, a static class will make things awkward.
My personal advice would be to make it an instance as this is more OO and would give you flexibility you might need in the future.
You have to be careful making this class static. In a web app, each request is handled on its own thread. Static utilities can be thread-unsafe if you are not careful. And if that happens you are not going to be happy.
I would highly recommend you follow the DAO pattern. Use a tool like Spring to make this easy for you. All you have to do is configure a datasource and your DB access and transactions will be a breeze.
If you go for a static class you will have to design it such that its largely stateless. The usual tactic is to create a base class with common data access functions and then derive them in specific classes for, say, loading Customers.
If object creation is actually the overhead in the entire operation, then you could also look at pooling pre-created objects. However, I highly doubt this is the case.
You might find that a lot of your common data access code could be made into static methods, but a static class for all data access seems like the design is lost somewhere.
Static classes don't have any issues with multi-threaded access per-se, but obviously locks and static or shared state is problematic.
By making the class static, you would have a hard time unit testing it, as then you
would probably have to manage internally the reading of the connection string in a non-clear manner, either by reading it inside the class from a configuration file or requesting it from some class that manages these constants. I'd rather instantiate such a class in a traditional way
var manager = new CompanyInfoManager(string connectionString /*...and possible other dependencies too*/)
and then assign it to a global/public static variable, if that makes sense for the class, ie
//this can be accessed globally
public static CompanyInfoManager = manager;
so now you would not sacrifice any flexibility for your unit tests, since all of the class's dependencies are passed to it through its constructor

Constructive criticism on this class

I've just reviewed some code that looked like this before
public class ProductChecker
{
// some std stuff
public ProductChecker(int AccountNumber)
{
var account = new AccountPersonalDetails(AccountNumber);
//Get some info from account and populate class fields
}
public bool ProductACriteriaPassed()
{
//return some criteria based on stuff in account class
//but now accessible in private fields
}
}
There has now been some extra criteria added which needs data not in the AccountPersonalDetails class
the new code looks like this
public class ProductChecker
{
// some std stuff
public ProductChecker(int AccountNumber)
{
var account = new AccountPersonalDetails(AccountNumber);
var otherinfo = getOtherInfo(AccountNumber)
//Get some info from account and populate class fields
}
public bool ProductACriteriaPassed()
{
//return some criteria based on stuff in account class
// but now accessible in private fields and other info
}
public otherinfo getOtherInfo(int AccountNumber)
{
//DIRECT CALL TO DB TO GET OTHERINFO
}
}
I'm bothered by the db part but can people spell out to me why this is wrong? Or is it?
In a layered view of your system, it looks like ProductChecker belongs to the business rules / business logic layer(s), so it shouldn't be "contaminated" with either user interaction functionality (that belongs in the layer(s) above) or -- and that's germane to your case -- storage functionality (that belongs in the layer(s) below).
The "other info" should be encapsulated in its own class for the storage layers, and that class should be the one handling persist/retrieve functionality (just like I imagine AccountPersonalDetails is doing for its own stuff). Whether the "personal details" and "other info" are best kept as separate classes or joined into one I can't tell from the info presented, but the option should be critically considered and carefully weighed.
The rule of thumb of keeping layers separate may feel rigid at times, and it's often tempting to shortcut it to add a feature by miscegenation of the layers -- but to keep your system maintainable and clean as it grows, I do almost invariably argue for layer separation whenever such a design issue arises. In OOP terms, it speaks to "strong cohesion but weak coupling"; but in a sense it's more fundamental than OOP since it also applies to other programming paradigms, and mixes thereof!-)
It seems like the extra data grabbed in getOtherInfo should be encapsulated as part of the AccountPersonalDetails class, and thus already part of your account variable in the constructor when you create a new AccountPersonalDetails object. You pass in AccountNumber to both, so why not make AccountPersonalDetails gather all the info you need? Then you won't have to tack on extra stuff externally, as you're doing now.
It definitely looks like there might be something going haywire with the design of the class...but it's hard to tell without knowing the complete architecture of the application.
First of all, if the OtherInfo object pertains to the Account rather than the Product you're checking on...it's introducing responsibilities to your class that shouldn't be there.
Second of all, if you have a Data Access layer...then the ProductChecker class should be using the Data Access layer to retrieve data from the database rather than making direct calls in to retrieve the data it needs.
Third of all, I'm not sure that the GetOtherInfo method needs to be public. It looks like something that should only be used internally to your class (if, in fact, it actually belongs there to begin with). In that case, you also shouldn't need to pass around the accountId (you class should hold that somewhere already).
But...if OtherInfo pertains to the Product you're checking on AND you have no real Data Access layer then I can see how this might be a valid design.
Still, I'm on your side. I don't like it.
considering that an accountNumber was passed into the constructor you shouldn't have to pass it to another method like that.
A few points
The parameter names are pascal case, instead of camel (this maybe a mistake)
getOtherInfo() looks like it's a responsibility of AccountPersonalDetails and so should be in that class
You may want to use a Façade class or Repository pattern to retrieve your AccountPersonalDetails instead of using a constructor
getOtherInfo() may also be relevant for this refactor, so the database logic isn't embedded inside the domain object, but in a service class (the Façade/Repository)
ProductACriteriaPassed() is in the right place
I would recommend this:
public class AccountPersonalDetails
{
public OtherInfo OtherInfo { get; private set; }
}
public class ProductChecker
{
public ProductChecker(AccountPersonalDetails) {}
}
// and here's the important piece
public class EitherServiceOrRepository
{
public static AccountPersonalDetails GetAccountDetailsByNumber(int accountNumber)
{
// access db here
}
// you may also feel like a bit more convinience via helpers
// this may be inside ProductCheckerService, though
public static ProductChecker GetProductChecker(int accountNumber)
{
return new ProductChecker(GetAccountDetailsByNumber(accountNumber));
}
}
I'm not expert in Domain-Driven Design but I believe this is what DDD is about. You keep your logic clean of DB concerns, moving this to external services/repositories. Will be glad if somebody correct me if I'm wrong.
Whats good. It looks like you have a productChecker with a nice clear purpose. Check products. You'd refactor or alter this because your have a need to. If you don't need to, you wouldn't. Here's what I would probably do.
It "feels" clunky to create a new instance of the class for each account number. A constructor argument should be something required for the class to behave correctly. Its a parameter of the class, not a dependency. It leads to the tempation to do a lot of work in the constructor. Usage of the class should look like this:
result = new ProductChecker().ProductACriteriaPassed(accountNumber)
Which I'd quickly rename to indicate it does work.
result = new ProductChecker().PassesProductACriteria(accountNumber)
A few others have mentioned that you may want to split out the database logic. You'd want to do this if you want unit tests that are fast. Most programs want unit tests (unless you are just playing around), and they are nicer if they are fast. They are fast when you can get the database out of the way.
Let's make a dummy object representing results of the database, and pass it to a method that determines whether the product passes. If not for testibility, this would be a private. Testability wins. Suppose I want to verify a rule such as "the product must be green if the account number is prime." This approach to unit testing works great without fancy infrastructure.
// Maybe this is just a number of items.
DataRequiredToEvaluateProduct data = // Fill in data
// Yes, the next method call could be static.
result = new ProductChecker().CheckCriteria(accountNumber, data)
// Assert result
Now we need to connect the database. The database is a dependency, its required for the class to behave correctly. It should be provided in the constructor.
public class ProductRepository {} // Define data access here.
// Use the ProductChecker as follows.
result = new ProductChecker(new ProductRepository()).CheckCriteria(accountNumber)
If the constructor gets annoyingly lengthy (it probably has to read a config file to find the database), create a factory to sort it out for you.
result = ProductCheckerFactory().GimmeProductChecker().CheckCriteria(accountNumber)
So far, I haven't used any infrastructure code. Typically, we'd make the above easier and prettier with mocks and dependency injection (I use rhinomocks and autofac). I won't go into that. That is only easier if you already have it in place.

C# : So if a static class is bad practice for storing global state info, what's a good alternative that offers the same convenience?

I've been noticing static classes getting a lot of bad rep on SO in regards to being used to store global information. (And global variables being scorned upon in general) I'd just like to know what a good alternative is for my example below...
I'm developing a WPF app, and many views of the data retrieved from my db are filtered based on the ID of the current logged in user. Similarly, certain points in my app should only be accessable to users who are deemed as 'admins'.
I'm currently storing a loggedInUserId and an isAdmin bool in a static class.
Various parts of my app need this info and I'm wondering why it's not ideal in this case, and what the alternatives are. It seems very convienient to get up and running.
The only thing I can think of as an alternative is to use an IoC Container to inject a Singleton instance into classes which need this global information, the classes could then talk to this through its interface. However, is this overkill / leading me into analysis paralysis?
Thanks in advance for any insight.
Update
So I'm leaning towards dependency injection via IoC as It would lend itself better to testability, as I could swap in a service that provides "global" info with a mock if needed. I suppose what remains is whether or not the injected object should be a singleton or static. :-)
Will prob pick Mark's answer although waiting to see if there's any more discussion. I don't think there's a right way as such. I'm just interested to see some discussion which would enlighten me as there seems to be a lot of "this is bad" "that is bad" statements on some similar questions without any constructive alternatives.
Update #2
So I picked Robert's answer seeing as it is a great alternative (I suppose alternative is a weird word, probably the One True Way seeing as it is built into the framework). It's not forcing me to create a static class/singleton (although it is thread static).
The only thing that still makes me curious is how this would have been tackled if the "global" data I had to store had nothing to do with User Authentication.
Forget Singletons and static data. That pattern of access is going to fail you at some time.
Create your own custom IPrincipal and replace Thread.CurrentPrincipal with it at a point where login is appropriate. You typically keep the reference to the current IIdentity.
In your routine where the user logs on, e.g. you have verified their credentials, attach your custom principal to the Thread.
IIdentity currentIdentity = System.Threading.Thread.CurrentPrincipal.Identity;
System.Threading.Thread.CurrentPrincipal
= new MyAppUser(1234,false,currentIdentity);
in ASP.Net you would also set the HttpContext.Current.User at the same time
public class MyAppUser : IPrincipal
{
private IIdentity _identity;
private UserId { get; private set; }
private IsAdmin { get; private set; } // perhaps use IsInRole
MyAppUser(userId, isAdmin, iIdentity)
{
if( iIdentity == null )
throw new ArgumentNullException("iIdentity");
UserId = userId;
IsAdmin = isAdmin;
_identity = iIdentity;
}
#region IPrincipal Members
public System.Security.Principal.IIdentity Identity
{
get { return _identity; }
}
// typically this stores a list of roles,
// but this conforms with the OP question
public bool IsInRole(string role)
{
if( "Admin".Equals(role) )
return IsAdmin;
throw new ArgumentException("Role " + role + " is not supported");
}
#endregion
}
This is the preferred way to do it, and it's in the framework for a reason. This way you can get at the user in a standard way.
We also do things like add properties if the user is anonymous (unknown) to support a scenario of mixed anonymous/logged-in authentication scenarios.
Additionally:
you can still use DI (Dependancy Injection) by injecting the Membership Service that retrieves / checks credentials.
you can use the Repository pattern to also gain access to the current MyAppUser (although arguably it's just making the cast to MyAppUser for you, there can be benefits to this)
There are many other answers here on SO that explains why statics (including Singleton) is bad for you, so I will not go into details (although I wholeheartedly second those sentiments).
As a general rule, DI is the way to go. You can then inject a service that can tell you anything you need to know about the environment.
However, since you are dealing with user information, Thread.CurrentPrincipal may be a viable alternative (although it is Thread Static).
For convenience, you can wrap a strongly typed User class around it.
I'd try a different approach. The static data class is going to get you in trouble -- this is from experience. You could have a User object (see #Robert Paulson's answer for a great way to do this) and pass that to every object as you construct it -- it might work for you but you'll get a lot template code that just repeats everywhere.
You could store all your objects in a database / encrypted file with the necessary permissions and then dynamically load all of them based on your Users permissions. With a simple admin form on the database, it's pretty easy to maintain (the file is a little bit harder).
You could create a RequiresAdminPermissionAttribute object to apply to all your sensitive objects and check it at run-time against your User object to conditionally load to objects.
While the route you're on now has merit, I think there are some better options to try.

Categories

Resources