private constructor and static constructor in singleton pattern - constructor

I'm a c# developer.
I have confused with private constructor and static constructor in singleton pattern.
Here is my sample code in below:
standard singleton pattern and it is thread safe:
public class SingletonTest
{
private static readonly Lazy<RedisCacheManager> CacheManager = new Lazy<RedisCacheManager>(() => new RedisCacheManager());
/// <summary>
/// singleton pattern
/// </summary>
private SingletonTest() { }
public static RedisCacheManager Instance
{
get { return CacheManager.Value; }
}
}
second it changed the private constructor to static constructor:
public class SingletonTest
{
private static readonly Lazy<RedisCacheManager> CacheManager = new Lazy<RedisCacheManager>(() => new RedisCacheManager());
/// <summary>
/// static(single object in our application)
/// </summary>
static SingletonTest() { }
public static RedisCacheManager Instance
{
get { return CacheManager.Value; }
}
}
And my question is the second code still one of the singleton pattern or just it always keep a only one object(RedisCacheManager) in our application?
Somebody help me,thanks.

So to answer you question, we need to go to basic.
Static constructors have the following properties:
A static constructor is called automatically to initialize the class before the first instance is created or any static members are
referenced.
A static constructor cannot be called directly.
If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for
the lifetime of the application domain in which your program is
running.
But for standard singleton pattern
It will be loaded, when we call it. So we have control over, when the singleton object will be created.
User has complete control when to call it.
Hope it answers your question.

Related

Custom Label Provider: Can't override Init() method

I'm trying to access a scaling factor in a viewModel through my CustomNumericLabelProvider.
I'm not quite sure what the best approach is, but I figured I might be able to access it through the parent axis if I used the Init(IAxis parentAxis) method which was shown in the LabelProvider documentation. I've given that a try, but now I'm getting an error telling me that "There is no suitable method for override".
If I comment out the Init() method, CustomNumericLabelProvider works great (with a hard-coded scaling factor).
Any idea why I'm receiving this error message? Or what another good approach would be to gain access to the scaling factor in my viewModel?
Note: I've also tried passing the viewModel into a custom constructor for the label provider (I was able to do something like this with viewportManager), however that didn't seem to work.
Here's the code (With the custom constructor, although I get the same error message without it)
public class CustomNumericLabelProvider : SciChart.Charting.Visuals.Axes.LabelProviders.NumericLabelProvider
{
// Optional: called when the label provider is attached to the axis
public override void Init(IAxis parentAxis) {
// here you can keep a reference to the axis. We assume there is a 1:1 relation
// between Axis and LabelProviders
base.Init(parentAxis);
}
/// <summary>
/// Formats a label for the axis from the specified data-value passed in
/// </summary>
/// <param name="dataValue">The data-value to format</param>
/// <returns>
/// The formatted label string
/// </returns>
public override string FormatLabel(IComparable dataValue)
{
// Note: Implement as you wish, converting Data-Value to string
var converted = (double)dataValue * .001 //TODO: Use scaling factor from viewModel
return converted.ToString();
// NOTES:
// dataValue is always a double.
// For a NumericAxis this is the double-representation of the data
}
}
I would propose passing the scaling factor into the constructor of the CustomNumericLabelProvider, and instantiating it in your viewmodel.
So your code becomes
public class CustomNumericLabelProvider : LabelProviderBase
{
private readonly double _scaleFactor;
public CustomNumericLabelProvider(double scaleFactor)
{
_scaleFactor = scaleFactor;
}
public override string FormatLabel(IComparable dataValue)
{
// TODO
}
public override string FormatCursorLabel(IComparable dataValue)
{
// TODO
}
}
public class MyViewModel : ViewModelBase
{
private CustomNumericLabelProvider _labelProvider = new CustomNumericLabelProvider(0.01);
public CustomNumericLabelProvider LabelProvider { get { return _labelProvider; } }
}
And you then bind to it as follows
<s:NumericAxis LabelProvider="{Binding LabelProvider}"/>
Assuming the datacontext of NumericAxis is your viewmodel.
Please be advised in SciChart v5 there will be new APIs for AxisBindings (similar to SeriesBinding) for dynamically creating axis in ViewModel. This will make dynamic axis in MVVM much easier. You can take SciChart v5 for a test-drive by accessing our WPF Chart Examples here.

JMockit mock protected method in superclass and still test method in real child class

I am still learning JMockit and need help understanding it.
I am testing a class that uses superclass methods. My test gets a null pointer when it attempts to use the superclass method due to code inside it that uses struts action context to get the session and pull an object from the session.
The method I want to bypass the struts session stuff inside the protected method.
public class MyExtendingClass extends MySuperClass{
public void methodIamTesting(){///}
}
public abstract class MySuperClass{
//I want to mock this method
protected Object myProtectedSuperClassMethod(){
// struts action context code that returns an object//}
}
Test code
#Test
public void testRunsAndDoesntPass() {
Mockit.setUpMock(MySuperClass.class, new MySuperClass(){
public Object myProtectedSuperClassMethod() {
return object;
}
});
// real class method invocation happens
assertEquals(expected, actual);
}
I keep getting NullPointers just like if I didn't have the mock
Not sure what to try next. All the docs and code samples I have read say to just declare the superclass method as public in the setUpMock and it should work.
I can't mock the entire class because that is the class I am testing.
I discovered that I needed to create the MockClass then reference it using setupmock correctly.
I am really falling in love with JMockit.
#MockClass(realClass = MyExtendingClass.class)
public static class MockSuperClass {
final Object object = new Object();
#Mock
public Object myProtectedSuperClassMethod() {
return object;
}}
#Test
public void testRunsAndNowWillPass() {
Mockit.setUpMock(MySuperClass.class, new MockSuperClass(){
public Object myProtectedSuperClassMethod() {
return object;
}});
// real class method invocation happens where i set expected and actual
assertEquals(expected, actual);
}
you mask the parent class implementation out totally #Mocked final MySuperClass base
abstract class MySuperClass{
protected Object myProtectedSuperClassMethod(){
}
class MyExtendingClass extends MySuperClass{
public void methodIamTesting(){///}
}
#Test
public void testRunsAndDoesntPass(#Mocked final MySuperClass base ) {
//you could mask out all the base class implementation like this
new Expectations(){{
invoke(base, "myProtectedSuperClassMethod");
}};
// real class method invocation happens
// ...
assertEquals(expected, actual);
}

s#arp castle injection

I have a soap web service in my web layer (s#arp architecture) which uses a service like this:
public ReportWebService(IReportService ReportService)
{
Check.Require(ReportService != null, "ReportService may not be null");
this.ReportService = ReportService;
}
Can someone please remind me how/where I configure the injection of the implementation for IReportService again?
Thanks.
Christian
The short answer is: Just put ReportService into yourProject.ApplicationServices and it will be injected.
The long answer is: In yourProject.Web in Global.asax you will find the method InitializeServiceLocator(). This calls the static method AddComponents on ComponentRegistrar.
ComponentRegistrar is located in yourProject.web/CastleWindsor. In there you will find
public static void AddComponentsTo(IWindsorContainer container)
{
AddGenericRepositoriesTo(container);
AddCustomRepositoriesTo(container);
AddApplicationServicesTo(container);
container.AddComponent("validator",
typeof(IValidator), typeof(Validator));
}
If you look at AddApplicationServicesTo you can see that is registers all types in yourProject.ApplicationServices (.WithService.FirstInterface()):
private static void AddApplicationServicesTo(IWindsorContainer container)
{
container.Register(
AllTypes.Pick()
.FromAssemblyNamed("NewittsStore.ApplicationServices")
.WithService.FirstInterface());
}
Here is from ComponentRegistrar.cs:
/// <summary>
/// The add application services to.
/// </summary>
/// <param name="container">
/// The container.
/// </param>
private static void AddApplicationServicesTo(IWindsorContainer container)
{
container.Register(AllTypes.Pick().FromAssemblyNamed("MyAssembly.ApplicationServices").WithService.FirstInterface());
}
and here is from the a service
private readonly IDocumentManagementService _client;
public DocumentService(IDocumentManagementService client)
{
_client = client;
}
This should help you out.

Actionscript 3: Can someone explain to me the concept of static variables and methods?

I'm learning AS3, and am a bit confused as to what a static variable or method does, or how it differs from a method or variable without this keyword. This should be simple enough to answer, I think.
static specifies that a variable, constant or method belongs to the class instead of the instances of the class. static variable, function or constant can be accessed without creating an instance of the class i.e SomeClass.staticVar. They are not inherited by any subclass and only classes (no interfaces) can have static members. A static function can not access any non-static members (variables, constants or functions) of the class and you can not use this or super inside a static function. Here is a simple example.
public class SomeClass
{
private var s:String;
public static constant i:Number;
public static var j:Number = 10;
public static function getJ():Number
{
return SomeClass.j;
}
public static function getSomeString():String
{
return "someString";
}
}
In the TestStatic, static variables and functions can be accessed without creating an instance of SomeClass.
public class TestStaic
{
public function TestStaic():void
{
trace(SomeClass.j); // prints 10
trace(SomeClass.getSomeString()); //prints "someString"
SomeClass.j++;
trace(SomeClass.j); //prints 11
}
}
A static variable or method is shared by all instances of a class. That's a pretty decent definition, but may not actually make it as clear as an example...
So in a class Foo maybe you'd want to have a static variable fooCounter to keep track of how many Foo's have been instantiated. (We'll just ignore thread safety for now).
public class Foo {
private static var fooCounter:int = 0;
public function Foo() {
super();
fooCounter++;
}
public static function howManyFoos():int {
return fooCounter;
}
}
So each time that you make a new Foo() in the above example, the counter gets incremented. So at any time if we want to know how many Foo's there are, we don't ask an instance for the value of the counter, we ask the Foo class since that information is "static" and applies to the entireFoo class.
var one:Foo = new Foo();
var two:Foo = new Foo();
trace("we have this many Foos: " + Foo.howManyFoos()); // should return 2
Another thing is static functions could only access static variables, and couldn't be override, see "hidden".

who calls the constructor witth parameter (Castle.Windsor)

I am learning castle.windsor following the tutorial online. this is the simple sample code:
public class Form1 {
private readonly HttpServiceWatcher serviceWatcher;
private System.ComponentModel.Container components = null;
public Form1()
{
InitializeComponent();
}
public Form1(HttpServiceWatcher serviceWatcher) : this()
{
this.serviceWatcher = serviceWatcher;
}
}
HttpServiceWatcher is in the xml conf file.
My question is: who is calling the constructor that has the parameter: public Form1(Http....) ?
at the program.cs i have this:
container.AddComponent("form.component",typeof(Form1));
Form1 form1 = (Form1) container["form.component"];
Application.Run(form1);
The container calls the constructor when it creates the requested object. The constructor that gets called is the constructor with the most arguments that the container can satisfy.
The dependency container itself creates the object (and thus calls the constructor).