make sure object only created by factory (C#) - c#

How do I make sure that a certain class is only instantiated by a factory and not by calling new directly?
EDIT: I need the factory to be a separate class (for dependency injection purposes) so I can't make it a static method of the class to be instantiated, and so I can't make new private.

If the factory is in the same assembly and you only need protection against external assemblies instantiating the class, you can make the constructor internal. The only way I know to prevent this for all other classes (including those in the same assembly) is to make the instantiated class a nested private class of the factory and only expose it as an interface. If the class is its own factory (a static factory method), then you can make the constructor private, as others have mentioned.

Make its constructors private and supply the factory method as a static method on the class itself.
In most cases you can just make the constructors internal, allowing you to break the factory out into its own class - I've found it's often not worth trying to prevent my own team from using new to create instances within the class' assembly.

If, for some reason, you need the factory and the constructed class to be in separate assemblies (which means simply using internal won't work), and you can ensure that your factory gets a chance to run first, you can do this:
// In factory assembly:
public class Factory
{
public Factory()
{
token = new object();
MyClass.StoreCreateToken(token);
}
public MyClass Create()
{
return new MyClass(token);
}
private object token;
}
// In other assembly:
public class MyClass
{
public static void StoreCreateToken(object token)
{
if (token != null) throw new InvalidOperationException(
"Only one factory can create MyClass.");
this.token = token;
}
public MyClass(object token)
{
if (this.token != token) throw new InvalidOperationException(
"Need an appropriate token to create MyClass.");
}
private static object token;
}
Yes, it's cumbersome and awkward. But there may be weird situations where this is actually a good solution.

Make the constructor internal and house the factory in the same assembly.
public MyClass
{
internal MyClass()
{
}
}
in same assembly
public MyClassGenerator
{
public static CreateMyClass()
{
return new MyClass();
}
}
If the factory can't be in the same assembly or this method doesn't work for you, look to Dan's answer

You can make your concrete classes as nested private classes with public constructors inside your factory class - this way your factory can create them, others can't even see them.
Anyway you return from factory some interface / abstract class, not concrete type.
Of course you won't be able to cast your return type to a concrete type somewhere in a client code but first it's a sign of bad design, second you can always workaround it with more concrete interface / abstract class your nested private class inherits.
you can refer to the Eric Lippert's answer here (for a similar problem):
Why Would I Ever Need to Use C# Nested Classes

It will always be created by calling new somewhere, but if you only want that to happen in your factory class, you can set all the constructors to Internal (or Private, and use a Public Static factory method on the same class).

Many people have mentioned using internal, but you can also make your constructors protected and derive a class that just has the static factory method in it. This doesn't prevent others from doing the same thing, but does a pretty good job at restricting direct access to your constructors.

I do not like to have the factory on the type itself especially if it is a domain object. Have it internal if you are having a separate class as factory (which I think you should). Use InternalVisible attribute if the factory is on the different assembly.

Related

Does making singleton class sealed really help in achieving goal of singleton pattern C# - Static Initialization (A thread safe solution)

I know other threads exist regarding this question but I couldn't find satisfactory answer for this. Why singleton class needs to be sealed in C# ? (To clarify my question)Does making it sealed really help it achieving goal of singleton (only one instance) ?
I have added more clarification about what I am wanting to know and trying to find reason for, hope readers understand what I am trying to discuss.
I am talking about MSDN article's thread safe solution :
https://msdn.microsoft.com/en-us/library/ff650316.aspx.
In this article first they give solution which is not thread safe, then they give another solution using static initialization to make it thread safe and in that solution they make class: sealed
As per MSDN's explanation -- The class is marked sealed to prevent derivation, which could add instances. For a discussion of the pros and cons of marking a class sealed, see [Sells03].
When I tried to figure why they used Sealed in static initialization approach, only thing I could figure is: as they wanted to prevent additional instantiation they made it sealed (this only prevents instantiation done through derivation, nested sub class derivation could create additional instances but by using Sealed it doesn't prevent nested class from creating additional instances.) to achieve goal of singleton. If using sealed doesn't prevent additional instantiation through other ways then why use it ?
Below is the MSDN's thread safe solution:
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton(){}
public static Singleton Instance
{
get
{
return instance;
}
}
}
My question is does MSDN's thread safe solution achieve goal of singleton by making it sealed? They made class sealed to prevent instantiation through derivation but that doesn't stop instantiation done through other ways. See my example below:
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton() { }
public static Singleton Instance
{
get
{
return instance;
}
}
public class nestedSingleton
{
public nestedSingleton()
{
Singleton moreThanOneObject = new Singleton();
}
}
}
Simply put: if anyone can derive from it, there can be multiple instances. So you definitely need some way of preventing arbitrary derivation.
Now you can simply rely on a private constructor to prevent subclassing instead (and you need the private constructor anyway), but the only reason for making a Singleton class unsealed would be if you wanted a nested type to be the implementation, e.g.
public class Singleton
{
public static Singleton Instance { get; }
= (DateTime.Now.Seconds & 1) == 0
? (Singleton) new EvenSingleton() : new OddSingleton();
private Singleton() {}
private class OddSingleton : Singleton {}
private class EvenSingleton : Singleton {}
}
This is properly a singleton - but it's a pretty unusual situation. It's vastly more common not to need a nested type to be the implementation, at which point it's clearer IMO to seal the singleton to make it clearer that you don't intend there to be any subclasses.
Basically it's communication as much as anything - a sealed class clearly prohibits derivation, whereas just having the private constructor (but no nested types) makes it more implicit. I think being explicit is clearer.
(Also, in earlier versions of C#, there are some bizarre ways you can get subclasses to compile with mutually recursive constructor calls so you never end up with a base constructor initializer. This has now been fixed, fortunately.)
To respond to a question addition:
Sealed keyword doesnt even make sense in this case if MSDN added it to prevent creating more instances of singleton by Nested sub classes.
In the example you've given, the nested class isn't a subclass. It looks like this:
public class nestedSingleton
whereas a nested subclass would look like this:
public class nestedSingleton : Singleton
(except ideally following .NET naming conventions).
It does not have to be
Implementing Singleton in C#
This is not safe on multithreads but a singleton
public class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
Making it sealed would make it not possible to inherit it (eliminating a possible cause for several instances of a singleton)
The reason is very tied to implementation details.
For example, see the following simple and wrong singleton implementation in C#:
public class A
{
private static readonly A _instance;
static A()
{
_instance = new A();
}
public static A Instance => _instance;
public string Name { get; set; }
}
Now let's derive it into B:
public class B : A
{
public string Surname { get; set; }
}
What would happen if you call B.Current static property?
// ERROR! Surname isn't a property of A
string surname = B.Instance.Surname;
One of main drawbacks of not sealing a singleton class is that static members are still accessible on derived classes. That is, it's very confusing that you can access Instance property on B but it returns the singleton instance of A.
You can't take this risk and one simple and yet powerful way of avoiding confusion is sealing A. Since A is a singleton implementation, you don't want to be inheritable, because derived classes can't expand the singleton.
If you're agree with the point of avoiding the described situation, a more convenient implementation of singleton could be:
// SEALED
public sealed class A
{
private static readonly A _instance;
// Avoid that other code excepting A class members
// can instantiate A
private A() {}
static A()
{
_instance = new A();
}
public static A Instance => _instance;
public string Name { get; set; }
}
About the criticism of using a static read-only field instead of lazy-loading the single instance...
I've also checked that some seem to be against my proposal of instantiating the single instance as part of static constructor or using a field initializer. I could also simplify the implementation as follows:
public sealed class A
{
private A() {}
private static readonly A _instance = new A();
public static A Instance => _instance;
public string Name { get; set; }
}
And, as far as I know, it provides more advantages than instantiating the single A instance in the Instance static property getter:
...
private static A _instance;
public static A Instance
{
get
{
if(_instance == null) _instance = new A();
return _instance;
}
}
See this other Q&A to understand that static constructors are thread-safe: Is the C# static constructor thread safe?
In response to my answer's criticism about my sample singleton implementation
In some comment, Jon Skeet has said:
A singleton doesn't just provide a single instance - it ensure that
it's the only instance ever created. See
en.wikipedia.org/wiki/Singleton_pattern "In software engineering, the
singleton pattern is a design pattern that restricts the instantiation
of a class to one object." Your code doesn't do that.
It's not a good argument to invalidate my sample implementation. For example, most inversion of control containers let you configure the life-cycle to singleton of a given component and its implementation.
The whole implementation is a regular public class with no constraint preventing you from even configuring the same implementation for other component, or you can even instantiate the implementation with new (i.e. new A()) wherever you want.
But the so-called component is a singleton, because you've configured that it will be a single instance of the whole component across the entire AppDomain.
Now let's see the Implementation section on Singleton pattern (Wikipedia):
Implementation of a singleton pattern must satisfy the single instance
and global access principles. It requires a mechanism to access the
singleton class member without creating a class object and a mechanism
to persist the value of class members among class objects. The
singleton pattern is implemented by creating a class with a method
that creates a new instance of the class if one does not exist. If an
instance already exists, it simply returns a reference to that object.
To make sure that the object cannot be instantiated any other way, the
constructor is made private. Note the distinction between a simple
static instance of a class and a singleton: although a singleton can
be implemented as a static instance, it can also be lazily
constructed, requiring no memory or resources until needed.
Comparing this implementation description with my sample implementation, I would say that the following implementation is a singleton:
public sealed class A
{
private A() {}
private static readonly A _instance = new A();
public static A Instance => _instance;
public string Name { get; set; }
}
You can't publicly instantiate it.
It can be only a single instance within a given AppDomain.
It provides global access to itself.
It implements a method to create the single instance, but it's using C# specific syntax and syntactic sugar.
It's lazily instantiated when the static Instance property is first instantiated. This is how static constructors and static class field initializers work in C#.
Now let's analyze the inversion of control container case:
Usually components are defined by interfaces and abstract classes. Few times are concrete classes. Thus, you can't instantiate an abstract class or interface.
There's no Instance static property, but the implementation description on Wikipedia says: [...] It requires a mechanism to access the singleton class member without creating a class object and a mechanism to persist the value of class members among class objects. The fact that you can implement this with an Instance static property of singleton class is just an implementation detail on some programming languages. The pattern description is fine with how inversion of control containers work. Either something like service locator anti-pattern or just dependency injection, are mechanisms that provide the single instance.
With inversion of control containers you can access singletons globally. For example, Container.Resolve<ISomeComponentConfiguredAsSingleton>(). BTW, excepting on few cases, service locator is considered an anti-pattern.
Most inversion of control containers can provide custom factories where you can define how the component implementation will be instantiated.
Based on previous point, you can easily implement a factory with lazy-loading.
In summary, I would say that in my particular case I've already left my ortodoxy and I assume that design patterns are abstract definitions to implement solutions to common problems and most are and should be language-agnostic. As long as my code works as the description of a given design pattern for me is enough to consider I'm implementing the whole design pattern. You can even implement singleton without calling your class WhateverSingleton.

Moving singleton definition into mixins in C#

I have to change around 10 classes into singletons and I thought that instead of copy-pasting the code it makes sense to use mixins, like it is described here: http://msdn.microsoft.com/en-us/vstudio/bb625996.aspx
However, I need not that much of additional methods, but more additional changes to the class itself, I have problems applying those instructions.
I tried to create an empty interface ISingleton and then to add the singleton part as extension to the new class public static class Singleton
This is singleton part which I would like to use:
public static SomeClass Instance
{
get { return _instance ?? (_instance = new SomeClass ()); }
}
private static SomeClass _instance;
But when adding it as extension I had a problem - how to define the Instance property, so it will be reusable by many classes?
And the second issue - I still need to change the constructors to private manually.
Does this approach makes any sense?
I haven't used mixins before, maybe this is just not the right scenario for it?
The mixins link you gave shows extension methods being used to add functionality to all objects supporting an interface. You still need to create the objects first. As singleton patterns handle the creation of objects it's basicly too soon to apply these techiniques.
Singleton needn't be so complicated, you're reading Jon Skeets article, a simple:
public sealed MyClass
{
private MyClass(){}
public static MyClass Instance = new MyClass();
}
Is often all you need. I'd happily repeat that code 10 times if needed. Or one can use a service locator or IoC container to manage the lifetime of objects.

Best way to prevent a class from being Instantiated?

I need to know how to prevent a class from being Instantiated in .net?
I know few methods like making the class Abstract and Static.
Is there any more way to achieve this?
Making the class static is the best approach, if you absolutely don't want any instances. This stops anyone from creating instances. The class will be both sealed and abstract, and won't have any constructors.
Additionally, the language will notice that it's a static class and stop you from using it in various places which imply instances, e.g. type arguments and variables. This indicates the intention more clearly than just having a private constructor - which could mean that there are instances, created within that class (e.g. for a singleton implementation).
Oh, and making the class static will stop you from introducing any pointless instance members in the class, too :)
See MSDN for more information about static classes.
Mark the constructor(s) private, protected or if in used from another assembly, internal
Marking the constructor private. Of course, this doesn't prevent the class from instantiating itself through a static method, for example...
More practically, what's the purpose of disallowing class instantiation. If it's to have a singleton, then a private constructor is appropriate. If it's to force subclassing, making the class abstract is better; if it's to have a class with utility methods, making it static is one way (then you can only have static methods).
I need to know how to prevent a class from being Instantiated in .net?
Your question is not clear.
Do you mean instantiated at runtime? Make the class abstract or static.
Do you mean that the constructor is not accessible in code? Make the constructor private. But note that someone could still use reflection to grab a handle on a constructor and instantiate an instance at runtime.
So, which do you mean?
If the question is:
How can you make your class not be instanced without having your class
be static or abstract?
Then the answer to this is to implement the singleton pattern, which in .NET 4+ this is done easily with:
public sealed class myClass
{
private static readonly Lazy<myClass> lazyInstance =
new Lazy<myClass>(() => new myClass());
public static Instance
{
get
{
return lazyInstance.Value;
}
}
private myClass()
{
// constructor logic here
}
}
The singleton pattern allows you to pass your class around as a reference to methods, while still ensuring that you have only a single instance of your class. It also makes testing much easier as you can have a ImyClass instance which myClass implements, this is very helpful when making mock objects.
Without .NET4 you can still implement the singleton pattern, for example:
private static readonly myClass instance = new myClass();
public static Instance
{
get
{
return instance;
}
}
// rest of code remains the same
Which doesn't have deferred loading until it's called, there's lots of other ways as well (I think about 6 different ways), but the above two are the most common ones.
In summary the question is likely asking if you know the singleton pattern and if you recognise it's importance over static classes for unit tests and mock objects.
As others have already pointed out, static fields, even those marked readonly can be set with reflection, in addition the private constructor can be called using reflection. If you need to prevent these, either you need to make the calling code run in a less trusted app-domain space, or you will need to implement your class as static.
Generally though, people don't bother with such levels of reflection to get around your constraints unless they 'really need to' for example, writing obscure / extreme fringe case unit tests.

How can I make a class global to the entire application?

I would like to access a class everywhere in my application, how can I do this?
To make it more clear, I have a class somewhere that use some code. I have an other class that use the same code. I do not want to duplicate so I would like to call the same code in both place by using something. In php I would just include("abc.php") in both... I do not want to create the object everytime I want to use the code.
Do you want to access the class or access an instance of the class from everywhere?
You can either make it a static class - public static class MyClass { } - or you can use the Singleton Pattern.
For the singleton pattern in its simplest form you can simply add a static property to the class (or some other class) that returns the same instance of the class like this:
public class MyClass
{
private static MyClass myClass;
public static MyClass MyClass
{
get { return myClass ?? (myClass = new MyClass()); }
}
private MyClass()
{
//private constructor makes it where this class can only be created by itself
}
}
The concept of global classes in C# is really just a simple matter of referencing the appropriate assembly containing the class. Once you have reference the needed assembly, you can refer to the class of choice either by it's fully qualified Type name, or by importing the namespace that contains the class. (Concrete instance or Static access to that class)
Or
You can have a Singleton class to use it everywhere but some people won't recommend you this way to proceed.
The other answers that you've been given about using a static class or a singleton pattern are correct.
Please consider, however, the fact that doing so does compromise your ability to test. In general, if you can, prefer dependency injection over globally accessed classes. I know this isn't always possible (or practical).
Just on that, you should also look up the abstract factory pattern. It allows you to have a well known factory class that produces the actual instance of a class that you're using. To have a globally accessed logging class, for example, don't directly create a logging class. Instead, use a logging factory to create it for you and return an interface to a logging class. That way it's easier to swap in and out different logging classes.
Since you do not want to create the object every time and it sounds like you are talking about some sort of utility methods...
I suggest you use static methods in an assembly which you can reference where needed

C#: How do I call a static method of a base class from a static method of a derived class?

In C#, I have base class Product and derived class Widget.
Product contains a static method MyMethod().
I want to call static method Product.MyMethod() from static method Widget.MyMethod().
I can't use the base keyword, because that only works with instance methods.
I can call Product.MyMethod() explicitly, but if I later change Widget to derive from another class, I have to revise the method.
Is there some syntax in C# similar to base that allows me to call a static method from a base class from a static method of a derived class?
static methods are basically a method to fallback from object oriented concepts. As a consequence, they are not very flexible in inheritance hierarchies and it's not possible to do such a thing directly.
The closest thing I can think of is a using directive.
using mybaseclass = Namespace.BaseClass;
class MyClass : mybaseclass {
static void MyMethod() { mybaseclass.BaseStaticMethod(); }
}
It can be done, but I don't recommend it.
public class Parent1
{
public static void Foo()
{
Console.WriteLine("Parent1");
}
}
public class Child : Parent1
{
public new static void Foo()
{
Type parent = typeof(Child).BaseType;
MethodInfo[] methods = parent.GetMethods();
MethodInfo foo = methods.First(m => m.Name == "Foo");
foo.Invoke(null, null);
}
}
Calling a static method using reflection is exactly the same as calling an instance method except that you pass null for the instance. You need FlattenHierarchy because it's defined in an ancestor.
var type = assy.GetType("MyNamespace.MyType");
MethodInfo mi = type.GetMethod("MyStaticMethod",
BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy);
mi.Invoke(null, null);
Further reading and thinking leaves me asking the same questions as others who have responded: why use static methods like this? Are you trying to do functional programming, and if so why not use lambda expressions instead? If you want polymophic behaviours with shared state, instance methods would be better.
It can be done:
public class Parent1
{
protected static void Foo()
{
Console.WriteLine("Parent1");
}
}
public class Child : Parent1
{
public static void Foo()
{
return Parent1.Foo();
}
}
Can be useful for unit testing protected static methods (for example).
First and foremost, if you're worried about re-parenting a class, then you're probably doing inheritance wrong. Inheritance should be used to establish "is-a" relationships, not simply foster code reuse. If you need code re-use alone, consider using delegation, rather than inheritance. I suppose you could introduce an intermediate type between a sub-type and its parent, but I would let that possibility drive my design.
Second, if you need to use functionality from the base class but extend it AND the use case calls for a static method, then you might want to consider using some external class to hold the functionality. The classic case for this in my mind is the Factory pattern. One way to implement the Factory pattern is through Factory Methods, a static method on a class that constructs an instance of that class. Usually the constructor is protected so that the factory method is the only way to build the class from outside.
One way to approach re-use with Factory Methods in an inheritance hierarchy would be to put the common code in a protected method and call that method from the Factory Method rather than directly call the base class Factory Method from a sub-types Factory Method. A better implementation might use the same technique but move the Factory Methods to a Factory class and use the constructor logic (internal now, not private), perhaps in conjunction with an initialization method(s), to create the object. If the behavior you are inheriting is external from the class (decryption/validation/etc), you can use shared methods (or composition) within the Factory to allow re-use between the Factory methods.
Without knowing the goal of your use of static methods it's difficult to give you an exact direction, but hopefully this will help.
Static methods are not polymorphic, so what you want to do is impossible.
Trying to find a way to treat static methods as polymorphic is possible but dangerous, because the language itself doesn't support it.
Some suggestions:
Reflection
Aliasing the base class (such as Mehrdad's example)
Having into account that a Static method shoudn't relay in instance data... you should have a static "MyMethod" that behaves diferent based on a parameter or something like that.
Remember that the static method defined in one class is just a way to order your code... but it is the same if that method is placed elsewhere... because it don't relay on the object where it is placed.
EDIT: I think your best choise is to use Product.MyMethod explicitly... If you think it... it should't be probable that your Widget change its base clase... and also in that case it is a minor change in code.
Static methods are "Class-Level" methods. They are intended to be methods that apply to all instances of a specific class. Thus, inheritance of this method does not make sense as it would change the meaning to apply to instances of the class. For instance, if you were looping through a collection of Products (some of Widget, some not) and called MyMethod on each Product then the method that was called would be determined by the instance of the class. This violates the purpose of static methods.
You can probably do something like you want more cleanly by simply not using static methods at all, because in your example it does not seem like MyMethod applies to all instances of Product. However, you can achieve the same affect you are describing by using an interface class like ‘IMyMethod’. This approach is still not using a static method. I guess I’m not seeing a need for a static method. Why do you want to use a static method to begin with?
It's very simple. Much simpler than using aliasing, reflections, etc. Maybe it's been made easier in newer additions of .NET, IDK, but this works perfectly fine. Just like with instance methods, accessing base methods doesn't require base be used, it is optional, usually necessary when the inheriting and base class have a method of the same name. Even without the base keyword, you can access the static methods of a base class as if they were in the class you are calling from. I only tested this when calling a base static method from a derived class's static method. Might not work if you are calling from an instance method to a static method.
public class BaseThings
{
protected static void AssertPermissions()
{
//something
}
}
public class Person:BaseThings
{
public static void ValidatePerson(Person person)
{
//just call the base static method as if it were in this class.
AssertPermissions();
}
}

Categories

Resources