Working example of a Singleton - singleton

In C#, I want to implement Singletons to provide data in one thread to many other threads.
I have decided to use this lazy form of Singleton from Jon Skeet (thanks, Jon!):
public sealed class Singleton
{
Singleton()
{
}
public static Singleton Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
So far, so good. ... but how does one use that?
What I want to do is share a single instance of the following data:
public bool myboolean = false ;
public double mydoubles[] = new double[128,3] ;
public IntPtr myhandles[] = new IntPtr[128] ;
How do I declare and reference these data as Singletons?
I also need them to be referenceable across different namespaces.
Many thanks!

// thread-safety
public sealed class Singleton
{
private static Singleton instance = null;
private static readonly object padlock = new object();
private bool myboolean = false;
private double[,] mydoubles = new double[128, 3];
private IntPtr[] myhandles = new IntPtr[128];
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
and to access
//Singleton.Instance.myboolean
//Singleton.Instance.mydoubles
//Singleton.Instance.myhandles

Related

(Polymorphism) Addition parameter pass to constructor of derived class in factory pattern

In factory pattern, we use a Factory class to produce a Product class that implement Abstract Product.
interface AbstractProduct {
public string getDetail();
}
class Product_A : AbstractProduct {
public string getDetail();
}
class Product_B : AbstractProduct {
public string getDetail();
}
class Factory {
public AbstractProduct produce(int product_id){
if (product_id == 1){
return Product_A();
}
else if (product_id == 2){
return Product_B();
}
}
}
int main() {
Factory factory = new Factory();
int id; // a random number either 1 or 2
print(factory.produce(id).getDetail());
}
My question is, what if today we need extract information to pass into Product_B from main(), for example a reference of a class instance.
int main() {
// object that need to be passed into Product_B
Database database = new Database();
Factory factory = new Factory();
int id; // a random number either 1 or 2
print(factory.produce(id).getDetail());
}
class Product_B : AbstractProduct {
public string getDetail() {
// I need the reference of database here.
// I'm unable to instance a database in side Product_B.
// I need to somehow pass it into Product_B.
database.query();
}
}
The only solution come to my mind is...
class Factory {
// pass the reference here
public AbstractProduct produce(int product_id, Database db){
if (product_id == 1){
return Product_A();
}
else if (product_id == 2){
return Product_B(db);
}
}
}
Is there any good solution or relative design pattern can solve this problem Elegant and Clean ? Thanks a lot.
The downside with your solution is that, every client of the Factory must have a Database in order to call the produce method.
So you can use the Abstract Factory pattern here:
interface AbstractFactory {
AbstractProduct produce();
}
class Factory_A implements AbstractFactory {
AbstractProduct produce() { return new Product_A(); }
}
class Factory_B implements AbstractFactory {
private Database db;
public Factory_B(Database db) { this.db = db; }
AbstractProduct produce() { return new Product_B(db); }
}
class Client {
private AbstractFactory factory;
public Client(AbstractFactory factory) { this.factory = factory; }
public void foo() {
AbstractProduct product = factory.produce();
// ...
}
}
void main() {
AbstractFactory factory = random() == 1 ?
new Factory_A() :
new Factory_B(new Database(...));
print(factory.produce().getDetail());
Client client = new Client(factory);
client.foo();
}
Hope this helps.

Session scoped instances in TinyIoC

I need an instance of a class to be created only once per user session. How do I register such a class with TinyIoC? I'm using NancyFx.
I ended up writing the following code:
public static class ContainerExtensions {
public static TinyIoCContainer.RegisterOptions SessionScoped<TRegisterType>(this TinyIoCContainer container, NancyContext context, Func<TRegisterType> factory) where TRegisterType : class
{
return container.Register<TRegisterType>((ctx, overloads) =>
{
var key = typeof(TRegisterType).FullName;
var instance = context.Request.Session[key] as TRegisterType;
if (instance == null) {
instance = factory();
context.Request.Session[key] = instance;
}
return instance;
});
}
}
I used the Nancy.Session.InProc NuGet.

Can MS Fakes create future mock objects?

In TypeMock you can create a future mock object, for example:
public class ClassToTest
{
public ClassToTest()
{
var o = new Foo();
}
}
[Test]
public void Test()
{
var fakeFoo = Isolate.Fake.Instance<Foo>();
Isolate.Swap.NextInstance<Foo>().With(fakeFoo);
}
Does MS Fakes have the same functionality as the above?
I found a great example from this SO question which demonstrates how to fake future instances of objects. Here's an example from that question:
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
ClassLibrary1.Child myChild = new ClassLibrary1.Child();
using (ShimsContext.Create())
{
ClassLibrary1.Fakes.ShimChild.AllInstances.addressGet = (instance) => "foo";
ClassLibrary1.Fakes.ShimParent.AllInstances.NameGet = (instance) => "bar";
Assert.AreEqual("foo", myChild.address);
Assert.AreEqual("bar", myChild.Name);
}
}
}
This looks like it will do the trick for me.

How to implement EF Code First and WCFDataService

A bit of history first. I created a EF Code First Library that contains POCO Objects as my Models, a generic DataProvider that inherits from DbContext, generic Repostory that implements the generic DataProvider, and a generic Service that implements the repository. I have used this library successfully in WPF (MVVM), ASP.Net, Window Forms, and ASP MVC applications.
For this discussion I will reference the Company Model
From the top down, I create a Service class called CompanyService that inherits from a base Service Class. The CompanyService class contains all of the business logic for the Company Model. This class uses the Repository class to perform the CRUD operations. The Repository then encapsulates all the DataProvider class operations.
I have done some research on using EF with WCFDataService, but I can't get my head around how to implement my library with it, particulary when it comes to overriding the CreateDataSource() Method.
It may be that I should just use a WCF Service instead, maybe I'm not understanding the purpose of the WCFDataService.
I have listed partial code for the classes involved:
public class CompanyService : ServiceBase<Company> ,ICompanyService
{
public Company GetCompanyByFolderId(string eFolderId)
{
return (Company)GetModelByFolderId(eFolderId);
}
}
public abstract class ServiceBase<TModel> : IService<TModel> where TModel : class, IModel
{
private IDataProvider _dataProvider;
public IDataProvider DataProvider
{
get
{
if (_dataProvider == null)
{
string connectionStringName = Properties.Settings.Default.DataProvider;
bool enableLazyLoading = true;
_dataProvider = new DataProvider(connectionStringName, enableLazyLoading);
}
return _dataProvider;
}
set
{
_dataProvider = value;
}
}
private IRepository<TModel> _repository;
public IRepository<TModel> Repository
{
get
{
if (_repository == null)
{
_repository = new Repository<TModel>(DataProvider);
}
return _repository;
}
set
{
_repository = value;
}
}
public TModel GetModelByFolderId(String folderId)
{
return GetTable().FirstOrDefault(o => o.EFolderid == folderId);
}
public virtual IQueryable<TModel> GetTable()
{
return Repository.GetTable();
}
}
public class Repository<TModel> : IRepository<TModel> where TModel : class, IModel
{
private IDataProvider _dataProvider;
public Repository(IDataProvider dataProvider)
{
_dataProvider = dataProvider;
}
private IDbSet<TModel> DbSet
{
get
{
return _dataProvider.Set<TModel>();
}
}
public IQueryable<TModel> GetTable()
{
return _dataProvider.GetTable<TModel>();
}
}
public class DataProvider : DbContext, IDataProvider
{
public DataProvider()
{
}
public DataProvider(string connectionStringName, bool enableLazyLoading = true)
: base(connectionStringName)
{
Configuration.LazyLoadingEnabled = enableLazyLoading;
//Configuration.ProxyCreationEnabled = false;
}
public new IDbSet<TModel> Set<TModel>() where TModel : class
{
return base.Set<TModel>();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new CompanyMapping());
base.OnModelCreating(modelBuilder);
}
public IQueryable<TModel> GetTable<TModel>() where TModel : class
{
return Set<TModel>().AsQueryable();
}
}
Then my Test looks something like this:
[TestClass()]
public class CompanyServiceTest
{
[TestMethod()]
public void GetCompanies()
{
CompanyService target = new CompanyService();
IQueryable<Company> companies = target.GetTable();
Assert.IsNotNull(companies);
}
[TestMethod()]
public void GetCompanyByFolderId()
{
CompanyService target = new CompanyService();
Company company = target.GetCompanyByFolderId("0000000000000000000000000172403");
Assert.IsNotNull(company);
}
}

Does Ninject support Func (auto generated factory)?

Autofac automatically generates factories for Func<T>; I can even pass parameters.
public class MyClass
{
public MyClass(Func<A> a, Func<int, B> b)
{
var _a = a();
var _b = b(1);
}
}
Can I do the same with Ninject? If not, what workaround can I apply?
Thanks.
Update:
Just found this post, seems the answer is no:
How do I handle classes with static methods with Ninject?
NB Ninject 3.0 and later has this fully supported using the Ninject.Extensions.Factory package, see the wiki:- https://github.com/ninject/ninject.extensions.factory/wiki
EDIT: NB there is a Bind<T>().ToFactory() implementation in Ninject 2.3 (which is not a fully tests supported release but is available from the CodeBetter server)
Ninject does not support this natively at the moment. We planned to add this to the next version. But support can be added easily by configuring the appropriate binding. Just load the module below and enjoy.
public class FuncModule : NinjectModule
{
public override void Load()
{
this.Kernel.Bind(typeof(Func<>)).ToMethod(CreateFunc).When(VerifyFactoryFunction);
}
private static bool VerifyFactoryFunction(IRequest request)
{
var genericArguments = request.Service.GetGenericArguments();
if (genericArguments.Count() != 1)
{
return false;
}
var instanceType = genericArguments.Single();
return request.ParentContext.Kernel.CanResolve(new Request(genericArguments[0], null, new IParameter[0], null, false, true)) ||
TypeIsSelfBindable(instanceType);
}
private static object CreateFunc(IContext ctx)
{
var functionFactoryType = typeof(FunctionFactory<>).MakeGenericType(ctx.GenericArguments);
var ctor = functionFactoryType.GetConstructors().Single();
var functionFactory = ctor.Invoke(new object[] { ctx.Kernel });
return functionFactoryType.GetMethod("Create").Invoke(functionFactory, new object[0]);
}
private static bool TypeIsSelfBindable(Type service)
{
return !service.IsInterface
&& !service.IsAbstract
&& !service.IsValueType
&& service != typeof(string)
&& !service.ContainsGenericParameters;
}
public class FunctionFactory<T>
{
private readonly IKernel kernel;
public FunctionFactory(IKernel kernel)
{
this.kernel = kernel;
}
public Func<T> Create()
{
return () => this.kernel.Get<T>();
}
}
}