What does exactly Dependency Injection in Symfony2 do? - dependency-injection

I registered my services.yml file like below :
services:
PMI.form.users_tasks:
class: PMI\UserBundle\Form\UsersTasksType
arguments:
EntityManager: "#doctrine.orm.default_entity_manager"
I can list it by php app/console container:debug, so that mean my service is registered properly.
In my UsersTasksType class I have like below :
class UsersTasksType extends AbstractType
{
protected $ur;
public function __construct(EntityManager $ur )
{
$this->setUr($ur);
}
// Get and setters
}
Does Dependency Injection mean that I don't have to pass the EntityManager to the class constructor anymore? Or what ?
Because when I have to run the code below :
$form = $this->createForm(new UsersTasksType(), $entity);
I get this error:
Catchable Fatal Error: Argument 1 passed to PMI\UserBundle\Form\UsersTasksType::__construct() must be an instance of Doctrine\ORM\EntityManager, none given, called in C:\wamp\www\PMI_sf2\src\PMI\UserBundle\Controller\UsersTasksController.php on line 74 and defined in C:\wamp\www\PMI_sf2\src\PMI\UserBundle\Form\UsersTasksType.php line 19
And I have to do something below :
$em = $this->container->get('doctrine.orm.entity_manager');
$form = $this->createForm(new UsersTasksType($em), $entity);
So what would be the whole purpose of Dependency Injection ?

Dependency Injection basically gives one service (in this case, your UserTasksType) access to another service (in this case, your the entity manager).
arguments:
EntityManager: "#doctrine.orm.default_entity_manager"
These two lines tell Symfony to expect the entity manager service to be passed into the constructor when you instantiate a new UserTasksType object, which effectively gives your UserTasksType access to the entity manager.
If you aren't using the entity manager in your UserTasksType, there is no need to inject it in the constructor and you could get rid of the two lines above and the __construct() / setUr() methods in your UserTasksType.
A better example to help you understand DIC might be that you have a service that is written specifically to send emails (Swiftmail, for e.g.) and you need to inject it into another service so that service can send emails.
By adding
arguments: [ #mailer ]
to your service definition, your services constructor will expect your mailer service
__construct ($mailer)
{
$this->mailer = $mailer;
}
which will give it access to send emails
someFunction()
{
//do something useful, then send an email using the swift mailer service
$this->mailer->sendEmail();
}
Check out the latest Symfony docs for more of an explanation.
http://symfony.com/doc/current/book/service_container.html

Related

Inject OSGi Services in a non-component class

Usually I have seen in OSGi development that one service binds to another service. However I am trying to inject an OSGi service in a non-service class.
Scenario trying to achieve: I have implemented a MessageBusListener which is an OSGi service and binds to couple of more services like QueueExecutor etc.
Now one of the tasks of the MessageBusListener is to create a FlowListener (non-service class) which would invoke the flows based on the message content. This FlowListener requires OSGi services like QueueExecutor to invoke the flow.
One of the approach I tried was to pass the reference of the services while creating the instance of FlowListener from MessageBusListener. However when the parameterized services are deactivated and activated back, I think OSGi service would create a new instance of a service and bind to MessageBusListener, but FlowListener would still have a stale reference.
#Component
public class MessageBusListener
{
private final AtomicReference<QueueExecutor> queueExecutor = new AtomicReference<>();
#Activate
protected void activate(Map<String, Object> osgiMap)
{
FlowListener f1 = new FlowListener(queueExeciutor)
}
Reference (service = QueueExecutor.class, cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.STATIC)
protected void bindQueueExecutor(QueueExecutor queueExecutor)
{
this.queueExecutor = queueExecutor;
}
}
public class FlowListener
{
private final AtomicReference<QueueExecutor> queueExecutor;
FlowListener(QueueExecutor queueExecutor)
{
this.queueExecutor = queueExecutor;
}
queueExecutor.doSomething() *// This would fail in case the QueueExecutor
service was deactivated and activated again*
}
Looking forward to other approaches which could suffice my requirement.
Your approach is correct you just need to also handle the deactivation if necessary.
If the QueueExecutor disappears the MessageBuslistener will be shut down. You can handle this using a #Deactivate method. In this method you can then also call a sutdown method of FlowListener.
If a new QeueExecutor service comes up then DS will create a new MessageBuslistener so all should be fine.
Btw. you can simply inject the QueueExecutor using:
#Reference
QueueExecutor queueExecutor;

Passing run-time data to services that are injected with Dependency Injection

My ASP.NET MVC application uses Dependency Injection to inject services to the controllers.
I need to find some way of passing run-time data to the services, because as far as I know it's anti-pattern to send run-time data to the constructors using DI.
In my case I have four different services that all rely on access tokens, which can be re-used between the services. However, that access token can expire so something needs to take care of issuing new access token when it expires.
The services (independent NuGet packages) are all clients for various services, that require access token for every request made. One example would be the AddUserAsync method in the IUserServiceBusiness, it basically POSTs to an endpoint with JSON data and adds Authorization header with bearer access token.
My current solution is to accept access token as a parameter in all of the methods in the services, which means that the web application takes care of handling the access tokens and passing them when needed.
But this solution smells, there has to be a better way of doing this.
Here's an example on how it's done currently.
The RegisterContainer method where all of the implementations are registered.
public static void RegisterContainers()
{
// Create a new Simple Injector container
var container = new Container();
container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();
SSOSettings ssoSettings = new SSOSettings(
new Uri(ConfigConstants.SSO.FrontendService),
ConfigConstants.SSO.CallbackUrl,
ConfigConstants.SSO.ClientId,
ConfigConstants.SSO.ClientSecret,
ConfigConstants.SSO.ScopesService);
UserSettings userSettings = new UserSettings(
new Uri(ConfigConstants.UserService.Url));
ICacheManager<object> cacheManager = CacheFactory.Build<object>(settings => settings.WithSystemRuntimeCacheHandle());
container.Register<IUserBusiness>(() => new UserServiceBusiness(userSettings));
container.Register<IAccessTokenBusiness>(() => new AccessTokenBusiness(ssoSettings, cacheManager));
container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
container.RegisterMvcIntegratedFilterProvider();
container.Verify();
DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
}
Implementation of IUserBusiness and IAccessTokenBusiness are injected to AccountController.
private readonly IUserBusiness _userBusiness;
private readonly IAccessTokenBusiness _accessTokenBusiness;
public AccountController(IUserBusiness userBusiness, IAccessTokenBusiness accessTokenBusiness)
{
_userBusiness = userBusiness;
_accessTokenBusiness = accessTokenBusiness;
}
Example endpoint in AccountController that updates the user's age:
public ActionResult UpdateUserAge(int age)
{
// Get accessToken from the Single Sign On service
string accessToken = _accessTokenBusiness.GetSSOAccessToken();
bool ageUpdated = _userBusiness.UpdateAge(age, accessToken);
return View(ageUpdated);
}
And here are some ideas that I've thought of:
Pass the access token to the services with a setter, in the constructor of the controllers. For example:
public HomeController(IUserBusiness userBusiness, IAccessTokenBusiness accessTokenBusiness)
{
_userBusiness = userBusiness;
_accessTokenBusiness = accessTokenBusiness;
string accessToken = _accessTokenBusiness.GetAccessToken();
_userBusiness.setAccessToken(accessToken);
}
I donĀ“t like this idea because then I would have to duplicate this code in every controller.
Pass the access token with every method on the services (currently doing this). For example:
public ActionResult UpdateUser(int newAge)
{
string accessToken = _accessTokenBusiness.GetAccessToken();
_userBusiness.UpdateAge(newAge, accessToken);
}
Works, but I don't like it.
Pass implementation of IAccessTokenBusiness to the constructor of the services. For example:
IAccessTokenBusiness accessTokenBusiness = new AccessTokenBusiness();
container.Register<IUserBusiness>(() => new IUserBusiness(accessTokenBusiness));
But I'm unsure how I would handle caching for the access tokens. Perhaps I can have the constructor of AccessTokenBusiness accept some generic ICache implementation, so that I'm not stuck with one caching framework.
I would love to hear how this could be solved in a clean and clever way.
Thanks!
As I see it, the requirement of having this access token for communication with external services is an implementation detail to the class that actually is responsible of calling that service. In your current solution you are leaking these implementation details, since the IUserBusiness abstraction exposes that token. This is a violation of the Dependency Inversion Principle that states:
Abstractions should not depend on details.
In case you ever change this IUserBusiness implementation to one that doesn't require an access token, it would mean you will have to make sweeping changes through your code base, which basically means you voilated the Open/close Principle.
The solution is to let the IUserBusiness implementation take the dependency on IAccessTokenBusiness itself. This means your code would look as follows:
// HomeController:
public HomeController(IUserBusiness userBusiness)
{
_userBusiness = userBusiness;
}
public ActionResult UpdateUser(int newAge)
{
bool ageUpdated = _userBusiness.UpdateAge(newAge);
return View(ageUpdated);
}
// UserBusiness
public UserBusiness(IAccessTokenBusiness accessTokenBusiness)
{
_accessTokenBusiness = accessTokenBusiness;
}
public bool UpdateAge(int age)
{
// Get accessToken from the Single Sign On service
string accessToken = _accessTokenBusiness.GetSSOAccessToken();
// Call external service using the access token
}
But I'm unsure how I would handle caching for the access tokens.
This is neither a concern of the controller nor the business logic. This is either a concern of the AccessTokenBusiness implementation or a decorator around IAccessTokenBusiness. Having a decorator is the most obvious solution, since that allows you to change caching independently of generation of access tokens.
Do note that you can simplify your configuration a bit by making use of the container's auto-wiring abilities. Instead of registering your classes using a delegate, you can let the container analyse the type's constructor and find out itself what to inject. Such registration looks as follows:
container.Register<IUserBusiness, UserServiceBusiness>();
container.Register<IAccessTokenBusiness, AccessTokenBusiness>();
ICacheManager<object> cacheManager =
CacheFactory.Build<object>(settings => settings.WithSystemRuntimeCacheHandle());
container.RegisterSingleton<ICacheManager<object>>(cacheManager);
Further more, a decorator for IAccessTokenBusiness can be added as follows:
container.RegisterDecorator<IAccessTokenBusiness, CachingAccessTokenBusinessDecorator>();

Unable to inject Entity Repository into service

I'm currently setting up an application with Symfony 3 and Doctrine 2.5 and I'm trying to inject an entity repository into a service and I keep getting the following error:
Type error: Argument 1 passed to UserService::setUserRepository() must
be an instance of UserRepository, instance of
Doctrine\ORM\EntityRepository given, called in
appDevDebugProjectContainer.php on line 373
This is how wire things up in my services.yml:
service_user:
class: UserService
calls:
- [setUserRepository, ["#service_user_repository"]]
service_user_repository:
class: UserRepository
factory: ["#doctrine.orm.entity_manager", getRepository]
arguments: [Entity\User]
This is my UserService:
<?php
class UserService {
protected $userRepository;
public function setUserRepository( UserRepository $userRepository )
{
$this->userRepository = $userRepository;
}
}
And this is my UserRepository:
<?php
use Doctrine\ORM\EntityRepository;
class UserRepository extends EntityRepository {
}
I have checked and double checked my namespaces and class names, all seem to check out fine.
How do I inject an entity repository into a service with Symfony 3 service wiring?
As mentioned in comment, everything you've showed looks fine.
But since you're getting from entity manager an EntityRepository instance instead of UserRepository, it means that you didn't configured User entity to have custom (UserRepository) repository class.
If you use YAML mapping, it should be something like:
Entity\User:
repositoryClass: UserRepository
# rest of mapping

Data access layer in c# with IOC(dependency injection)

I am trying to build a multilayer application (service) in C#. To be precise, I am trying to build a REST webservice with ASP.NET Web Api which will be hosted on my own (with Owin). Now I got so far that I have the following components(every one of them is in a separate .dll):
- RestHost (which in my case is an console application)
- RestService (here is my web service witch all the controllers)
- InterfacesLayer
- ModelLayer (here are the objects I use, just with their get/set methods)
- DataLayer (every single class inside of ModelLayer has its own class in Datalayer, plus there is the Database connection class)
- BusinessLayer (here all the logic is done, again every class from model has its own class, and this layer communicates with the REST service and the datalayer).
RestHost - as the name says, it is the host of my service. Besides that I am also doing my dependency injection here. Since it is not much code I will post it:
static void Main(string[] args)
{
IUnityContainer container = new UnityContainer();
// Dependency Resolving
container.RegisterType<IAktData, AktDataImpl>(new HierarchicalLifetimeManager());
container.RegisterType<IAktService, AktServiceImpl>(new HierarchicalLifetimeManager());
container.RegisterType<ILeistungData, LeistungDataImpl>(new HierarchicalLifetimeManager());
container.RegisterType<ILeistungService, LeistungServiceImpl>(new HierarchicalLifetimeManager());
container.RegisterType<IPersonData, PersonDataImpl>(new HierarchicalLifetimeManager());
container.RegisterType<IPersonService, PersonServiceImpl>(new HierarchicalLifetimeManager());
container.RegisterType<IPersistent, FirebirdDB>(new HierarchicalLifetimeManager());
string serverAddress = ConfigurationManager.AppSettings["serverAddress"];
string connectionString = ConfigurationManager.ConnectionStrings["connectionStrings"].ConnectionString;
using (RESTService.StartServer(container, serverAddress,connectionString ))
{
Console.WriteLine("Server started # "+ DateTime.Now.ToString() + " on " + serverAddress + "/api");
Console.ReadLine();
}
}
Oh and what I forgot to mention, but you can see it from the code, in my host application I am also reading the App.Config where my connection string is hosted.
And here is my problem. I am not sure how to access the Database Connection from my service. Here I am implementing Firebird in my data access layer, but I am unsure how to use it in my application. Of course the easiest way would be just to create an instance and pass it to my service but this is the last thing i want to do. I have also been thinking implementing Firebird as a static class or as a singleton, but then i cannot use my IPersistant interface (and besides that, i don't think that this is the right approach).
So my question would be, is there any best practice for this kind of stuff? I somehow need to pass the connectionstring to the implementation of IPersistent (Firebird) but without actually creating an instance of Firebird in my RESTService.
Thanks
The general pattern for a multi-layer application like the one you're building is to have a data layer that provides your services with access to a database, or some other method of persisting data, usually via a repository.
You can then configure your IoC container to inject your connection string into your repository and then inject your repository into your service. This way your service stays agnostic as to how data is persisted and can focus on defining the business logic.
I actually do a similar thing for a repository that instead of persisting data in a database, stores it in a blob on Azure's CDN. The configuration withing my IoC (StructureMap in my case) looks like this:
string storageApiKey = ConfigurationManager.AppSettings["CloudStorageApiKey"];
string storageUsername = ConfigurationManager.AppSettings["CloudStorageUsername"];
this.For<IImageStorageRepository>().Use<ImageStorageRepository>().Ctor<string>("storageApiKey").Is(storageApiKey).Ctor<string>("storageUsername").Is(storageUsername);
With my repository looking like this:
public class ImageStorageRepository : IImageStorageRepository
{
....
public ImageStorageRepository(string storageApiKey, string storageUsername)
{
this.cloudIdentity = new CloudIdentity() { APIKey = storageApiKey, Username = storageUsername };
this.cloudFilesProvider = new CloudFilesProvider(cloudIdentity);
}
....
}

How do you output the context class using log4net as a service?

I am using Log4Net as a service which is injected into other services using StructureMap.
How do I ensure the log file includes the calling service class context (class name and/or thread) which is making the log4net calls?
Surely the calling class or thread will always be the logging service which doesn't help me understand where the logging calls are really coming from.
EDIT:
Register code:
ObjectFactory.Initialize(x =>
{
x.For<ILog>().AlwaysUnique().Use(s => s.ParentType == null ?
LogManager.GetLogger(s.BuildStack.Current.ConcreteType) :
LogManager.GetLogger(s.ParentType));
});
Service layer:
public class LoggerService : ILoggerService
{
private readonly ILog log;
public LoggerService(ILog logger)
{
log = logger;
log.Info("Logger started {0}".With(logger.Logger.Name));
}
public void Info(string message)
{
log.Info(message);
}
}
In the logging, I am still always getting the LoggerService as the context so I'll never see what actually called the logger. It doesn't seem to be working correctly. I feel like I'm missing something here...
Edit 2:
I've added a pastie link for a console app here:
http://pastie.org/1897389
I would expect the parent class to be logged but it isn't working at the simplest of levels.
You might want to have a look at Castle Dynamic proxy in order to solve it using AOP. There is an example of using it with Structure Map on the Structure Map Google Group.
Ayende has an example of AOP based logging using Log4Net and Windsor.
I use StructureMap in a lot of the code I generate and I have a StructureMap registry which I use to hook the logger into the context of the class that it is injected into.
For Reference, I'm using the 2.6.2 version of StructureMap but should be fine with 2.5+ where the new .For<>().Use<>() format is utilized.
public class CommonsRegistry : Registry
{
public CommonsRegistry()
{
For<ILogger>().AlwaysUnique().Use(s => s.ParentType == null ? new Log4NetLogger(s.BuildStack.Current.ConcreteType) : new Log4NetLogger(s.ParentType.UnderlyingSystemType.Name));
XmlConfigurator.ConfigureAndWatch(new FileInfo(Path.Combine(Path.GetDirectoryName(Assembly.GetAssembly(GetType()).Location), "Log.config")));
}
}
What this registry is doing is for anywhere the ILogger is injected, use the class that it's injected into is where the logging messages are logged to/context of.
*Also, in the second line (XmlConfigurator.ConfigureAndWatch) is where I tell Log4Net to get the logging information from the file "Log.config" instead of the application configuration file, you may or may not like that and can be omitted.
The code I use is a common IOC.Startup routine where I would pass if I would like to use the default registery.
ObjectFactory.Initialize(x =>
{
x.AddRegistry<CommonsRegistry>();
...
}
This gives me the calling class name in the logging instance where messages are logged to automatically and all that is required is to inject the logger into the class.
class foo
{
private readonly ILogger _log;
public foo(ILogger log)
{
_log = log;
}
}
Now the messages are logged as context/class "foo".

Resources