Dependency Injection and Runtime Constructor Parameters - c#

I will use a very simple example to describe my questions. Let's say I have a class to handle database calls
public class DatabaseAccessLayer : IDatabaseAccessLayer
{
public DatabaseAccessLayer(string uid, string password, string server)
{
// build connection object and so on
}
}
Then I have a class to use it
public class MyBusinessService : IBusinessService
{
public MyBusinessService(IDatabaseAccessLayer dal)
{
}
}
If I use Unity as example, I would typically wire up the IoC container this way
container.RegisterType<IDatabaseAccessLayer, DatabaseAccessLayer>(new InjectionConstructor("my_uid", "my_password", "my_server"));
container.RegisterType<IBusinessService, MyBusinessService>();
It works well if I define the parameters as known values when the IoC container is set up as application starts, for example typical web application has the values in the configuration file.
However there is one requirement that I have to pass the parameters (uid, password, server) to data access layer class for every single business service call because the values could be different each time. It looks like I have no way to use IoC container in this case.
Anybody has some comments, shall I abandon IoC container in this case or there is a better way to use IoC container?

Related

Why using the factory pattern when a simple dependecy injection is enough

Im looking to this example to understand the use of factory pattern.
I'm really amator in this field so excuse my silly question.
My problem is that i don't see the use of the factory pattern which return us the interface that we can inject it directly when we need to use it.
In the example above I would do something like this:
public class Program
{
// register the interfaces with DI container in a separate config class (Unity in this case)
private readonly IShippingStrategy _shippingStrategy;
public Program(IShippingStrategy shippingStrategy)
{
_shippingStrategy= shippingStrategy;
}
public int DoTheWork(Order order)
{
// assign properties just as an example
order.ShippingMethod = "Fedex";
order.OrderTotal = 90;
order.OrderWeight = 12;
order.OrderZipCode = 98109;
int shippingCost = _shippingStrategy.CalculateShippingCost(order);
return shippingCost;
}
}
Instead of injecting the factory :
public class Program
{
// register the interfaces with DI container in a separate config class (Unity in this case)
private readonly IShippingStrategyFactory _shippingStrategyFactory;
public Program(IShippingStrategyFactory shippingStrategyFactory)
{
_shippingStrategyFactory = shippingStrategyFactory;
}
public int DoTheWork(Order order)
{
// assign properties just as an example
order.ShippingMethod = "Fedex";
order.OrderTotal = 90;
order.OrderWeight = 12;
order.OrderZipCode = 98109;
IShippingStrategy shippingStrategy = _shippingStrategyFactory.GetShippingStrategy(order);
int shippingCost = shippingStrategy.CalculateShippingCost(order);
return shippingCost;
}
}
Why taking the bruden to create a factory (thus adding an extra layer) when we can inject the interface directly to wherever we need to use it ?
I think you don't want just another article about the factory pattern but a short comprehensive answer.
So, I'd like to focus on two things.
More flexibility
Most commonly, you'd set up your composition root where you basically say ...
"if anyone wants IAnyService, he should get MyAnyServiceImplementation".
This is fixed for your application. Once set up, your dependency injection container will serve the class instances you registered but you should not try to re-configure that container again. That's perfect for startup flexibility like registering implementation for data access components by the application's configuration, for example. Say ...
"if anyone wants IUserRepository, he should get MsSqlUserRepository because we are working with MSSQL server".
Of course, having that "immutable" composition root limits the possibilities to choose an implementation in runtime depending of the applications' state.
Instead you can inject a class which decides on a current state which service implementation to choose. Data validation is a typical scenario for that pattern because there might be different rules for different entities on your system. The buzzword here is "rule pattern" or "strategy pattern".
Lifetime control
Think of a long-living class instance like a view (user interface) or any class attached to it (like a viewmodel or a controller). As long as a user is active on a view, the class is alive. By injecting a class instance to the constructor of the view controller, for example, you hold an active instance of it as long as the view lives.
Let's say you want to use a data repository to connect to a database for example. These database access calls should be short and you do not want to keep connections open for a long time. With a repository factory, you could control the lifetime very precisely and make sure that the class is removed after it has been used:
using (var repository = new _factory.CreateRepository(...))
{
return repository.GetAnything();
}
With this, a very lightweight class - the factory - gets injected and lives as long as the view controller lives. The heavy classes - the connection things - should not live long and are just created when needed.
In fact, chances are that the repository is not instantiated at all if there's no requirement to load the data (because of an upfront cache hit, for example). If you would have injected the repository directly, you'd guarantee that one long living instance lives in memory in every case.
If you check the code for the factory you can see that depending on the ShippingMethod of the order a different implementation of the IShippingStrategy is returned by the factory. Since the ShippingMethod is only known once DoTheWork has been called it's impossible to inject the right implementation when the class is constructed (and the same class might even need different implementations for different orders).

Global Variables in ASP.NET MVC 4

I'm currently building an ASP.Net MVC 4 SAAS application (C#) and am stuck on designing the plans. I mean if a customer picks Plan A they should have access to some things and if they pick Plan B they get access to others and so on.
The Part that I'm stuck on is be best practice of sharing the account's plan with all of the actions. I realize having global variables are bad practice and all but I really don't want to take round trips to the DB to get the plan on every action.
What I'm thinking of doing is something like This SO answer where they just declare a static model and set it at some point and access it later on. In your opinion, is this the best way of doing this? is there a better way?
I think best practice is you should include an IoC in your project and inject a configuration object to your controller.
Example code of a controller:
public class YourController : Controller
{
private IConfigService _configService;
//inject your configuration object here.
public YourController(IConfigService configService){
// A guard clause to ensure we have a config object or there is something wrong
if (configService == null){
throw new ArgumentNullException("configService");
}
_configService = configService;
}
}
You could configure your IoC to specify singleton scope for this configuration object. In case you need to apply this pattern to all your controllers, you could create a base controller class to reuse code.
Your IConfigService
public interface IConfigService
{
string ConfiguredPlan{ get; }
}
Your ConfigService:
public class ConfigService : IConfigService
{
private string _ConfiguredPlan = null;
public string ConfiguredPlan
{
get
{
if (_ConfiguredPlan == null){
//load configured plan from DB
}
return _ConfiguredPlan;
}
}
}
This class is easily extended to include more configurations like connection String, Default timeout,...
We're passing in an interface to our controller class, it's easy for us to mock this object during unit testing.

Domain Driven Design: access a configured value from an Entity without using a Service Locator

I have a User entity which has a HasCompletedSecurity property which indicates whether that particular User has answered the number of security questions required by the system. The number of security questions the system requires is configurable and retrieved from a config file. How should the User class access the configured information?
I currently have an IConfigurationService interface behind which I have implementations which use the ConfigurationManager or the Azure equivalent if it is available. I've encapsulated access to my DI container through a static InjectionService class, and am currently resolving the configured value like so:
public class User
{
private static readonly IConfigurationService _configurationService =
InjectionService.Resolve<IConfigurationService>();
public bool HasCompletedSecurity
{
get
{
// Uses the static _configurationService to get the
// configured value:
int numberOfRequiredResponses =
GetConfiguredNumberOfRequiredResponses();
return this.SecurityQuestionResponses.Count()
>=
GetConfiguredNumberOfRequiredResponses();
}
}
}
This is of course an example of the ServiceLocator anti-pattern, and I don't like it one bit. The static dependency makes unit testing anything which uses this class awkward.
I'm using the Entity Framework and taking a cue from here I don't want to pass my entities through a DI container to give them their dependencies, so... how should I be accessing the configured value instead?
Edit: With this exact example to one side (and I do appreciate the suggestions as to the correct architecture for it), the larger question I'm interested in is how do you manage non-static references to services from entities? Is the answer to just architect the entities in such a way that you never need to?
Here's how I would define the User class:
public class User
{
public bool HasCompletedSecurity { get; set; }
// other members...
}
Seriously, this is a better solution because it decouples the value along the temporal dimension. Consider this: if a user completed all security questions in 2010 and you later on change the business rule, are you then going to invalidate the existing user?
In most cases it would probably be more reasonable to record and persist that sometime in the past, the user completed the security procedure that was in effect at that time. In that way, you don't bother existing users.
You can still using the concept of Inversion of Control without using any sort IoC container or requiring its use in the constructor of your entity. I would approach this using a quasi-strategy pattern and have something like:
public interface ISecurityPolicy
{
public int MinimumSecurityQuestionResponses { get; }
}
public class User
{
public void HasCompletedSecurity (ISecurityPolicy security_policy)
{
return this.SecurityQuestionResponses.Count()
>= security_policy.MinimumSecurityQuestionResponses;
}
}
This puts the onus of providing the particular security policy that the user must satisfy on the caller, not the User class itself.
From that point on, you can provide that extra parameter however you want to, maybe be wrapping this in a IUserSecurityService that will have the ISecurityPolicy injected into the service, etc.
This is still Inversion of Control, but it's at the method level, since this one particular method is really the only one that cares about the security policy/configuration.

IoC/DI in the face of winforms and other generated code

When using dependency injection (DI) and inversion of control (IoC) objects will typically have a constructor that accepts the set of dependencies required for the object to function properly.
For example, if I have a form that requires a service to populate a combo box you might see something like this:
// my files
public interface IDataService {
IList<MyData> GetData();
}
public interface IComboDataService {
IList<MyComboData> GetComboData();
}
public partial class PopulatedForm : BaseForm {
private IDataService service;
public PopulatedForm(IDataService service) {
//...
InitializeComponent();
}
}
This works fine at the top level, I just use my IoC container to resolve the dependencies:
var form = ioc.Resolve<PopulatedForm>();
But in the face of generated code, this gets harder. In winforms a second file composing the rest of the partial class is generated. This file references other components, such as custom controls, and uses no-args constructors to create such controls:
// generated file: PopulatedForm.Designer.cs
public partial class PopulatedForm {
private void InitializeComponent() {
this.customComboBox = new UserCreatedComboBox();
// customComboBox has an IComboDataService dependency
}
}
Since this is generated code, I can't pass in the dependencies and there's no easy way to have my IoC container automatically inject all the dependencies.
One solution is to pass in the dependencies of each child component to PopulatedForm even though it may not need them directly, such as with the IComboDataService required by the UserCreatedComboBox. I then have the responsibility to make sure that the dependencies are provided through various properties or setter methods. Then, my PopulatedForm constructor might look as follows:
public PopulatedForm(IDataService service, IComboDataService comboDataService) {
this.service = service;
InitializeComponent();
this.customComboBox.ComboDataService = comboDataService;
}
Another possible solution is to have the no-args constructor to do the necessary resolution:
public class UserCreatedComboBox {
private IComboDataService comboDataService;
public UserCreatedComboBox() {
if (!DesignMode && IoC.Instance != null) {
comboDataService = Ioc.Instance.Resolve<IComboDataService>();
}
}
}
Neither solution is particularly good. What patterns and alternatives are available to more capably handle dependency-injection in the face of generated code? I'd love to see both general solutions, such as patterns, and ones specific to C#, Winforms, and Autofac.
I believe there is no silver-bullet solution here. I would use property injection in this case to leave parameterless constructor. Also I personally do not like injection of services into UI classes, I prefer injecting some kind of Presenters there. Then you have a property Presenter which will be set by IoC container and in setter of this property you will have your initializing code.
Out of your two solutions I do not like second one especially because of referencing IoC container in your code which is bad IMO.
I would say that your UI, especially sub-elements of your UI, shouldn't need to be provided with any services.
It's hard to judge how feasible this is for your app, but MVC or MVP is meant to avoid this need.
I would try to redesign so that a controller is responsible for interacting with services and that controller gives the view elements everything they need, rather than letting the view elements ask for what they need.

Is this basically what an IOC like NInject does?

Normally I would do this:
public class DBFactory
{
public UserDAO GetUserDao()
{
return new UserDao();
}
}
Where UserDao being the concrete implementation of IUserDao.
So now my code will be littered with:
DBFactory factory = new DBFactory();
IUserDao userDao = factory.GetUserDao();
User user = userDao.GetById(1);
Now if I wanted to swap implementaitons, I would have to go to my DBFactory and change my code to call a different implementation.
Now if I used NINject, I would bind the specific implementation on application startup, or via a config file. (or bind based on specific parameters etc. etc.).
Is that all there is too it? Or is there more?
(reason I am asking if I want to know how it will help me here: Help designing a order manager class)
In a word, yes. Your code would then change in structure, so your dependencies would be passed in via the constructor (or setters, which I am personally not a fan of). You would no longer say "new XXX()" for services in the body of your methods.
You also would not likely need the factory anymore at all, since the DI framework can act as a factory. You would likely just need a constructor dependency on IUserDAO.
So something like:
public class ClassThatNeedsUserDAO
{
private readonly IUserDAO _userDAO;
public ClassThatNeedsUserDAO(IUserDAO userDAO)
{
_userDAO = userDAO;
}
public User MyMethod(userId)
{
return _userDAO.GetById(int userId);
}
}
There is more to it, one example would be if the constructor of UserDao required some other objects to be passed as arguments (dependencies).
You could have ninject automatically create and inject those objects, saving some lines of code but more importantly ensuring that every class is loosely coupled with its dependencies.

Categories