Im considering, whether class which gonna communicate with database should be a singleton.
Instead of injecting context everywhere it's needed, I've created one inside Database class, which is the singleton class.
Is it good practice?
Code:
class DatabaseService
{
public FreelanceOrganizerDataContext DatabaseContext { get; private set; } = new FreelanceOrganizerDataContext();
static DatabaseService _singleton = new DatabaseService();
private DatabaseService() { }
public static DatabaseService GetDatabaseService()
{
return _singleton;
}
//Save Section
public void AddProject()
{
}
public void AddCustomer()
{
}
//etc
}
I would recommend using an IoC such as Unity or Autofac. You can do things such as Inject Dependecies into your classes, control the lifecycle of the objects (when and how often they are instantiated), and better set yourself up for Unit Tests.
Related
We are building an application where we have to have both old and new version to work side by side (V1 is old and V2 is new). Now to handle new flow we are using same old interfaces with everything being the same and differs only in functionality, hence now we have to define a named instance in-order to resolve the instances for new flow.
In the process teams have started using Service Factory Pattern as shown below
class DataProcessor
{
private readonly IDataManager _dataManager;
public DataProcessor(IServiceFactory serviceFactory)
{
_dataManager = serviceFactory.GetInstance<IDataManager>();
}
public void Execute()
{
_dataManager.Run();
}
}
Service Factory Class
public class ServiceFactory : IServiceFactory
{
private readonly IFeatureEvaluator _featureEvaluator;
public ServiceFactory(IFeatureEvaluator featureEvaluator)
{
_featureEvaluator = featureEvaluator;
}
public T GetInstance<T>()
{
if (_featureEvaluator.IsEnabled<"V2">())
{
return ObjectFactory.GetInstance<T>("V2")
}
return ObjectFactory.GetInstance<T>();
}
}
Since Service Factory is anti-pattern and also it creates lot of complexities in retiring the old flow in future, I would want a way to initialize the dependencies at the container(structuremap ioc) itself or to work in a "Pure DI" way so that we can avoid headache. Any idea on how to tackle this.
Update:
IDataManager Implementation
public interface IDataManager
{
void Run();
}
public class OldFlow : IDataManager
{
public void Run()
{
//
}
}
public class NewFlow : IDataManager
{
public void Run()
{
//
}
}
IDataManager has 2 implementations and resolving the instance should be based on _featureEvaluator, if V2 flow then "newflow" should be instantiated else "old flow" instance
Why don't you just inject the dependency you need?
public class DataProcessor
{
private readonly IDataManager _dataManager;
public DataProcessor(IDataManager dataManager)
{
_dataManager = dataManager;
}
public void Execute()
{
_dataManager.Run();
}
}
In your Composition Root you can conditionally compose DataProcessor with the implementation of IDataManager you'd like:
public DataProcessor CreateDataProcessor()
{
if (_featureEvaluator.IsEnabled<"V2">())
{
IDataManager dm = new NewFlow();
return new DataProcessor(dm);
}
IDataManager dm = new OldFlow();
return new DataProcessor(dm);
}
This seems to be similar to feature toggles. Why, by the way, is _featureEvaluator an interface? Wouldn't a bool suffice?
I am currently designing an API and I have run into a design issue I'm not sure how to approach.
I have a customer facing class that depends on another class from within the model. I need to test the Customer Facing class because it contains business logic.
Normally I would use Dependency Injection to handle this case, like this contrived example:
public interface IRunQuery
{
ResultObject RunQuery();
}
public class CustomerFacing
{
public CustomerFacing(IRunQuery needed)
{
Needed = needed;
}
IRunQuery Needed { get; }
public void DoSomethingForCustomer()
{
// Do some stuff.
result = Needed.RunQuery();
// Do some more stuff.
}
}
I inject a Stub of the IRunQuery interface when unit testing; it is an expensive operation. This has one enormous glaring issue, though. IRunQuery is not to be known about by the customer. They shouldn't need to know about it and the constructor for CustomerFacing should be:
public CustomerFacing() { }
How do I Unit Test CustomerFacing without injecting the dependency in the constructor?
you could have 2 constructors: one for unit tests where you inject the dependency, and one that is for production, that creates the dependency some other way, possibly calling the other ctor. lookup "poor-man's DI":
class MyClass
{
public MyClass(IService service)
{
this.Service = service;
}
public MyClass() : this(new Service())
{
}
}
I used "Property Injection" to solve this issue.
"IRunQuery" has a very reasonable default value. It is only in the testing case that it needs to be modified. I can define it as internal which obscures it from consumer eyes while still allowing tests to modify it before it is accessed.
public interface IRunQuery
{
ResultObject RunQuery();
}
public class CustomerFacing
{
public CustomerFacing()
{
}
private IRunQuery _needed = null;
internal IRunQuery Needed
{
get
{
if (_needed = null)
{
_needed = new StandardQuery();
}
return _needed;
}
set
{
_needed = value;
}
}
public void DoSomethingForCustomer()
{
// Do some stuff.
result = Needed.RunQuery();
// Do some more stuff.
}
}
Thanks for the help everyone.
I am having to re-write a large WinForms application and I want to use MVC to allow increased testing capability etc. I want to also adopt Ninject as my IoC container as it is lightweight, fast and will increase the exstensibility of my application going forward.
I have done a great deal of reading and I have managed to make a start on the arcitecture of this new application. However, I am not sure i have the right idea when using Ninject. The code...
Starting with Program.cs and related classes...
static class Program
{
[STAThread]
static void Main()
{
FileLogHandler fileLogHandler = new FileLogHandler(Utils.GetLogFilePath());
Log.LogHandler = fileLogHandler;
Log.Trace("Program.Main(): Logging initialized");
CompositionRoot.Initialize(new ApplicationModule());
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(CompositionRoot.Resolve<ApplicationShellView>());
}
}
public class CompositionRoot
{
private static IKernel _ninjectKernel;
public static void Initialize(INinjectModule module)
{
_ninjectKernel = new StandardKernel(module);
}
public static T Resolve<T>()
{
return _ninjectKernel.Get<T>();
}
}
public class ApplicationModule : NinjectModule
{
public override void Load()
{
Bind(typeof(IApplicationShellView)).To(typeof(ApplicationShellView));
}
}
An my ApplicationShellView is
public partial class ApplicationShellView : Form, IApplicationShellView
{
public ApplicationShellView()
{
InitializeComponent();
}
public void InitializeView()
{
dockPanel.Theme = vS2012LightTheme;
}
}
with interface
public interface IApplicationShellView
{
void InitializeView();
}
The controller for this view is
public class ApplicationShellController
{
private IApplicationShellView view;
public ApplicationShellController(IApplicationShellView view)
{
view.InitializeView();
}
}
Currently the controller is redundant, and although this code works and my view displays, I have some important questions...
Should I be using the ApplicationShellController to initialize my form, currently this is not using MVC "pattern"?
It feels like I have written a Service Locator, and from what I have read, this is bad. How else should I be using Ninject for IoC to initialize my application?
Any other advice as to what I am doing right[if anything!]/wrong?
Thanks very much for your time.
No you should not be initializing your controller, this exactly what IoC and Ninject are for. When you initialize your view/form, Ninject should make the view fetch the controller it depends on, which will auto fetch controllers it depends on and so on.
Of course this won't work like you've set it up right now. For starters, your view needs to know the controller it depends on.
public partial class ApplicationShellView : Form, IApplicationShellView
{
private IApplicationShellController _controller;
public ApplicationShellView()
{
InitializeComponent();
init();
//InitializeView()
}
private void init() {
_controller = NinjectProgram.Kernel.Get<IApplicationShellController>();
//Because your view knows the controller you can always pass himself as parameter or even use setter to inject
//For example: _controller.SetView1(this);
}
public void InitializeView()
{
dockPanel.Theme = vS2012LightTheme;
}
}
public class ApplicationShellController : IApplicationShellController
{
//Implementes functionality for the MainForm.
public ApplicationShellController()
{
//Also possible to add other controllers with DI
}
}
This does indeed look like a Service Locator, simply initializing your view should do be sufficient.
public class NinjectProgram
{
//Gets the inject kernal for the program.
public static IKernel Kernel { get; protected set; }
}
public class Program : NinjectProgram
{
[STAThread]
private static void Main()
{
Kernel = new StandardKernel();
Kernel.Load(new ApplicationModule());
Application.Run(new ApplicationShellView());
}
}
public class ApplicationModule : NinjectModule
{
public override void Load()
{
//Here is where we define what implementations map to what interfaces.
Bind<IApplicationShellController>().To<ApplicationShellController>();
//We can also load other modules this project depends on.
Kernel.Load(new NinjectModule());
}
}
Don't try and make it too complicated, a good start is important but you can always apply changes when and where needed during development.
I believe the following GitHub project might be a good starting point: Example of how you might use Ninject within a WinForms application.
If you have any more questions, just leave a comment and I'll try to answer them as soon as possible
Short question
Where should I put the abstract factory interface and the actual factory?
Overview
I'm writing a simple video transcoding application and I'm trying to wrap my head around dependency injection.
I have separated my application into several projects in visual studio.
One class library for the transcoder, used by the application engine
One class library for the application engine that will be used by a gui or console interface
One console application that will be the main user interface for now
Without DI
This is what everything looks like before dependency injection
The transcoder lib:
namespace SimpleFFmpeg {
public interface ITranscoder {
void Transcode(String fileName);
}
public class Transcoder:ITranscoder {
// ...
public void Transcode(String fileName) {
// do transcoding stuff
}
// ...
}
}
The PusherEngine lib:
using SimpleFFmpeg;
namespace PusherLib {
public class PusherEngine {
private readonly List<VideoItem> _items;
public PusherEngine() {
_items = new List<VideoItem>();
}
// ...
public void processItems() {
foreach (VideoItem item in _items) {
ITranscoder t = new Transcoder();
t.Transcode(item.FileName);
}
}
// ...
}
}
The actual application:
namespace Pusher {
class Program {
static void Main(string[] args) {
PusherEngine pe = new PusherEngine();
pe.addVideoItem(new VideoItem(...));
pe.processItems();
}
}
}
Refactor to use DI
I create a generic abstract factory interface, like suggested in this question: Creating new instances while still using Dependency Injection
public interface IFactory<T> {
T Get();
}
Next I create a factory that creates ITranscoders
public class TranscoderFactory: IFactory<ITranscoder> {
public ITranscoder Get() {
return new SimpleFFmpeg.Transcoder();
}
}
Then I modify the PusherEngine to require a factory dependence in the constructor:
using SimpleFFmpeg;
namespace PusherLib {
public class PusherEngine {
private readonly IFactory<ITranscoder> _transcoderFactory;
private readonly List<VideoItem> _items;
public PusherEngine(IFactory<ITranscoder> transcoderFactory) {
_items = new List<VideoItem>();
_transcoderFactory = transcoderFactory;
}
// ...
public void processItems() {
foreach (VideoItem item in _items) {
ITranscoder t = _transcoderFactory.Get();
t.Transcode(item.FileName);
}
}
// ...
}
}
Finally, in the Program it looks like this:
namespace Pusher {
class Program {
static void Main(string[] args) {
IFactory<ITranscoder> f = new TranscoderFactory();
PusherEngine pe = new PusherEngine(f);
pe.addVideoItem(new VideoItem(...));
pe.processItems();
}
}
}
Question
In which lib/project should the IFactory interface be defined?
In which lib/project should the TranscoderFactory be defined?
Do they live in the Transcoder lib? In the PusherLib? Or in the actual frontend application?
I'm looking for best practices.
Thanks!
In my opinion, it doesn't matter. For me, the main point of dependency injection is being able to inject something other than the real implementation while testing. I keep my unit tests in a separate project along with the various mock definitions used for testing. The real implementations as well as the 'abstract' logic are all kept in the same assembly/project/namespace.
If you really need a factory (see comment), then this blog post by Mark Seemann addresses this issue.
Briefly, if you use the IoC Container in your factory, you want to use it in the composition root. If not, there is no harm for it to remain in the same assembly as the class it is instantiating.
EDIT
For your particular case, you do not need a factory, since you already have everything you need to solve this dependency.
using SimpleFFmpeg;
namespace PusherLib {
public class PusherEngine {
private readonly ITranscoder _transcoder;
private readonly List<VideoItem> _items;
public PusherEngine(ITranscoder transcoder) {
_items = new List<VideoItem>();
_transcoder = transcoder;
}
// ...
public void processItems() {
foreach (VideoItem item in _items) {
_transcoder.Transcode(item.FileName);
}
}
// ...
}
}
The initialization would then look like this:
namespace Pusher {
class Program {
static void Main(string[] args) {
ITranscoder t = new Transcoder();
PusherEngine pe = new PusherEngine(t);
pe.addVideoItem(new VideoItem(...));
pe.processItems();
}
}
}
The reason why a factory was needed in the answer you linked is that the dependency needed values only known at run-time to be able to be instantiated, while your dependency does not require run-time dependent arguments to be created.
To answer your actual question, and not if this is a good use case for a factory or not:
For this purpose I sometimes split up Interface and Implementation into different projects, and something like your IFactory<> would live in the Common.I project.
This doesn't work in every scenario, but one of the advantages of this approach for me is that I can swap out Implementation dll's with either mocks or a new implementation when there are underlying technology changes.
For example, we recently switched from parsing xml files from a directory to getting data from a service. The only thing I had to update on client machines was this one Implementation dll because the interface did not change at all.
But I guess in the end it doesn't really matter, as mentioned before.
I ran into a problem today and a friend recommended I use a global static instance or more elegantly a singleton pattern. I spent a few hours reading about singletons but a few things still escape me.
Background:
What Im trying to accomplish is creating an instance of an API and use this one instance in all my classes (as opposed to making a new connection, etc).
There seems to be about 100 ways of creating a singleton but with some help from yoda I found some thread safe examples. ..so given the following code:
public sealed class Singleton
{
public static Singleton Instance { get; private set; }
private Singleton()
{
APIClass api = new APIClass(); //Can this be done?
}
static Singleton() { Instance = new Singleton(); }
}
How/Where would you instantiate the this new class and how should it be called from a separate class?
EDIT:
I realize the Singleton class can be called with something like
Singleton obj1 = Singleton.Instance();
but would I be able to access the methods within the APIs Class (ie. obj1.Start)? (not that I need to, just asking)
EDIT #2: I might have been a bit premature in checking the answer but I do have one small thing that is still causing me problems. The API is launching just fine, unfortunately Im able to launch two instances?
New Code
public sealed class SingletonAPI
{
public static SingletonAPI Instance { get; private set; }
private SingletonAPI() {}
static SingletonAPI() { Instance = new SingletonAPI(); }
// API method:
public void Start() { API myAPI = new API();}
}
but if I try to do something like this...
SingletonAPI api = SingletonAPI.Instance;
api.Start();
SingletonAPI api2 = SingletonAPI.Instance; // This was just for testing.
api2.Start();
I get an error saying that I cannot start more than one instance.
Why not just add a public APIClass property to your singleton?
public sealed class Singleton
{
public static Singleton Instance { get; private set; }
private APIClass _APIClass;
private Singleton()
{
_APIClass = new APIClass();
}
public APIClass API { get { return _APIClass; } }
static Singleton() { Instance = new Singleton(); }
}
Then your calling site looks like:
Singleton.Instance.API.DoSomething();
Or if you are the author of the API class, you could make it a singleton itself, instead of wrapping it in a singleton:
public sealed class SingletonAPI
{
public static SingletonAPI Instance { get; private set; }
private SingletonAPI() {}
static SingletonAPI() { Instance = new SingletonAPI(); }
// API method:
public void DoSomething() { Console.WriteLine("hi"); }
}
API call:
SingletonAPI.Instance.DoSomething();
Here is the official Microsoft approach.
The beauty of the singleton is that you can use and access it anywhere in your code without having to create an instance of the class. In fact that is it's raison d'etre, a single instance of a class eg
Singleton.Instance.MyValue and Singleton.Instance.DoSomething();
You wouldn't instantiate the class - the pattern you're using basically instantiates itself the first time it's used. The advantage to the method you're using is that it's thread safe (will only instantiate once, no matter how many threads try to access it), lazy (it won't instantiate until you try to access the Singleton class), and simple in implementation.
All you need to do to use this is to do:
Singleton.Instance.MyMethodOnSingleton();
Or, alternatively:
Singleton myInstance = Singleton.Instance; // Will always be the same instance...
myInstance.DoSomething();