How to set up a locale in ZF2 from browser preferences? - translation

In Zend framework 1 I can do
try {
$locale = new Zend_Locale('browser');
} catch (Zend_Locale_Exception $e) {
$locale = new Zend_Locale('en');
}
$registry = Zend_Registry::getInstance();
$registry->set('Zend_Locale', $locale);
But how does it work with Zend Framework 2?

I recently blogged about Zend Framework 2 and how all the i18n, l10n and locale settings work. This might be interesting for you, too, as the locale used can be set up by many ways.
Read about it: Zend Framework 2 - translate, i18n, locale
Personally i go with the following approach and then - depending on your structure - you may add locales from either database, session or cookies or whatever ;)
<?php
namespace FileManager;
use Zend\Mvc\ModuleRouteListener;
class Module
{
public function onBootstrap($e)
{
$translator = $e->getApplication()->getServiceManager()->get('translator');
$translator
->setLocale(\Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']))
->setFallbackLocale('en_US');
}
//...
}

Judging from this RFC, the decision was taken to leave Zend_Locale out of Zend Framework 2 and rely on the core PHP I18n classes.
I would recommend reading the manual starting with the introduction to get a good understanding of the classes and then refactoring your code to use them.

Related

How do you call a Service outside of a Symfony3 controller? And queries from Repository

I have two questions today. This is detailed because too many other replies rely on assumptions and have not been detailed enough. I hope that this is detailed and will be able to help lots of developers.
1st. The code below points to the real question I have. How do you call a Service outside of the controller since the $this->get() method is inside of the controller only? This is not in any of the documentation or on KNP University's tutorial on Services.
2nd. From what I have read, according to some, not all, if you call to a Repository, from anywhere, it should automatically instantiate the Entity Repository. I don't think this is so. Tell me if I am right or wrong.
See the following below....
My Default Controller, it's straightforward call a class and let it do some work. As an example, I called it with a Service and a conventional OO method:
<?php
// src/AppBundle/Controller/DefaultController.php
// Here is where I am starting. There is a service
// and there is a conventional OO call.
// Both should invoke the same thing.
namespace AppBundle\Controller;
use AppBundle\Service;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
class DefaultController extends Controller
{
/**
* #Route("/", name="homepage")
*/
public function indexAction(Request $request)
{
// Step 1.... Do a little of this.
// Step 2.... Do some of that.
// Step 3.... Call another class to do some logic and it will
// eventually call a query...
// Invoking my service
$obj_via_service = $this->get('app.services.process_question');
$result1 = $obj_via_service->submitQuestion();
// Invoking via Namespace and Call
$obj_via_new = new Service\ProcessQuestion();
$result2 = $obj_via_new->submitQuestion();
dump($result1);
dump($result2);
die();
}
}
My Service.yml File.
# src/app/config/services.yml
parameters:
services:
app.services.process_question:
class: AppBundle\Service\ProcessQuestion
app.rep.geo_state:
class: AppBundle\Entity\GeoStateRepository
arguments: ['#doctrine.orm.entity_manager']
This is my class that is doing the work for me. I want to be able to call the second service ^^above^^ but I can't because I can't use $this->get() outside of the controller.
<?php
// src/AppBundle/Service/ProcessQuestion.php
namespace AppBundle\Service;
class ProcessQuestion
{
public function submitQuestion()
{
// Step 1.... Do this.
// Step 2.... Do that.
// Step 3.... Query for some data...
// Invoke my repository class via a Service Call....
// but I cannot do that because 'get' is a part of the
// controller...
$obj_via_service = $this->get('app.rep.geo_state');
**^^ ^^**
**^^ This is what won't work ^^**
$results = $obj_via_service->selectStates();
return $results;
}
}
My Repository Class... Keep in mind I cannot reach this class yet, but I am throwing it in here so that other new Symfony 3 developers can see this.
<?php
// src/AppBundle/Repository/GeoState.php
// My Repository Class where I want to do some queries...
namespace AppBundle\Repository;
use Doctrine\ORM\EntityRepository;
class GeoStateRepository extends EntityRepository
{
/**
* #Mapping\Column(type="string")
*/
private $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
public function selectStates()
{
$sql = "SELECT * FROM geo_state";
return $this->getEntityManager()->createQuery($sql)->getResult();
}
}
Why is this so hard to find an example? Also, I have followed a bunch of the Symfony 2.x documentation and the nuances are hard to port into Symfony 3 sometimes.
I think Fabian re purposed too much of the docs for 2.x to go into 3.x and there is not any good examples on coding that is between the New Developer level and the Hard Core Developer level. If you are at Sensio and reading this, please keep in mind that there is a middle ground we need to cover and most of the screencasts that out there and much of the better documentation is not in English.
You should really read more about Dependency Injection.
Symfony is very good at this .
Regarding your question about using app.rep.geo_state service in the app.services.process_question service .
In Symfony/ DI terminology it's can be termed as injecting a service into another service .
The documentation on how to do this is very good.
this is how it can be done.
services:
app.services.process_question:
class: AppBundle\Service\ProcessQuestion
arguments: ['#app.rep.geo_state']
app.rep.geo_state:
class: AppBundle\Entity\GeoStateRepository
arguments: ['#doctrine.orm.entity_manager']
And in the class
<?php
// src/AppBundle/Service/ProcessQuestion.php
namespace AppBundle\Service;
use AppBundle\Entity\GeoStateRepository;
class ProcessQuestion
{
private $geoRepository;
public function __construct(GeoStateRepository $geoRepository)
{
$this->geoRepository = $geoRepository;
}
public function submitQuestion()
{
//now you can call $this->geoRepository
}
}
Also note that $this->get() is only a shortcut function provided by the Symfony base Controller class to access the container.
To know more about DI, you can read Fabian's excellent articles about this in his blog .

Use ZF2 controller plugins for application services within an DDD?

I am currently using DDD (Domain Driven Design) for a new Zend Framework 2 project. Everything works fine but I do have a question regarding the application services.
I understood that application services are located at the application layer and are kind of the entry point to the domain logic. They can access domain services or the repository for example.
I wonder now if it would make sense to implement the application services as controller plugins. In a classical MVC application this controller plugin could handle the results from the called domain services or repositories. Depending on these results they could generate a redirect response or pass data / a form to a ViewModel. If this logic is encapsulated within a plugin my controller only has to call the plugin and return the result of the plugin.
Am I totally wrong about this? Or would you rather keep the logic how to react on results of a domain service or a repository in a controller?
Best Regards,
Ralf
Of course it's kind of subjective and people have strong opinions about things like that... so here's mine:
Controller plugins contain code that's universal to any MVC/REST
action and business logic is not universal. Plugins are supposed to facilitate the
"controlling" of request/response and not the business logic that's
down on the model level. Linking it there would make it less
reusable, e.g. for console actions. Also it'd make it less probable
to use the business logic with some other framework.
It's awkward to test. Injecting controller plugins as controller
class constructor parameters would be kinda redundant, since they are already
available from the plugin manager injected into AbstractActionController or AbstractRestfulController. Not having the dependencies injected in a obivious/visible way (like trough contructor method) makes it harder to figure out what the controller class actually depends
on. Also since all plugins (AbstractPlugin related) depend on controller instance, switching context from
http to console (like for a phpunit test) might get problematic. Also testing logic
written/made available as controller plugin would sooner or later
escalate to including request/response objects in the tests and
that's unnecessary complexity.
It's not intuitive. When I hear plugin I think of something small.
Not a full-blown business logic code buried under such inconspicuous
name. So when I have little time to debug someones code the last
thing I need it to things be out of place like that.
Again I'd like to reiterate, that's just my opinion. I've learned that a lot of patterns can crumble under a weird-enough use case, but the above points made sense to me and my team so far.
As an example for my solution here you can see an controller action:
public function showAction()
{
$service = $this->readProductEntityCommand;
$service->setId($this->params()->fromRoute('id'));
try {
$result = $service->execute();
} catch (ProductException $e) {
$this->flashMessenger()->addMessage($e->getMessage());
return $this->redirect()->toRoute('part3/product');
}
return new ViewModel(
array(
'productEntity' => $result->getData(),
)
);
}
And here is an example of an application service build as an command object
class ReadProductEntityCommand implements CommandInterface
{
protected $productRepository;
protected $id;
public function __construct(ProductRepositoryInterface $productRepository)
{
$this->productRepository = $productRepository;
}
public function setId($id)
{
$this->id = $id;
}
public function execute()
{
if (is_null($this->id)) {
throw new ProductIdInvalidException(
'Produkt ID wurde nicht angegeben.'
);
}
try {
$product = $this->productRepository->getProduct(
new ProductIdCriterion(
new ProductId($this->id)
)
);
} catch (\Exception $e) {
throw new ProductNotFoundException(
'Es konnten kein Produkt gelesen werden.'
);
}
if ($product === false) {
throw new ProductNotFoundException('Produkt wurde nicht gefunden.');
}
$result = new Result();
$result->setValid(true);
$result->setData($product);
$result->setMessage('Produkt wurde gelesen.');
return $result;
}
}
Maybe this helps someone in the future.

Routing nested controllers using IoC for dependency injection in laravel 3

update: if i can achieve same result using a different approach, please enlighten me.
I'm using/learning laravel 3 while building my project. Before coding any page-content at all, I'm verifying if i can deploy everything as planned, since this project is an actual rewrite of a rather huge app which is seriously outdated in the techniques it uses.
I'm struggling at this last part, which is quite possibly the hardest challenge i'll face to setup my project.
URL:
site.com/shops/__identifier__/controller/action/params
The above is the uri i'm trying to code atm.
The _identifier_ part should become a model (eloquent based)
the shops is the base for nested controllers
ie:
controllers/
- shops/
- home.php
- contact.php
- products.php
- etc ....
Each existing uri shops/identifier is a real site on its own. (though it has a different domain offcourse)
I want all my nested shops controllers to know what shop they're working with. In fact, the identifier will be used to load the correct layouts, to render the correct images, contact details etc...
From what i've read, i'll need to use the IoC functionality to inject the dependency of my shop-model into the constructor of my controller.
this is what i have atm:
file:application/start.php
/**
* Register IoC container for my nested shop controllers
*/
IoC::register('controller: shop', function($controller, $identifier)
{
//also tried using same line without the \\
$class = '\\Shops_' . ucfirst($controller) . '_Controller';
return new $class($identifier);
});
file:application/routes.php
/**
* Register all shop routes
*/
Route::any('/shops/(:any)/(:any?)/(:any?)', function($identifier, $controller = "home", $method = "index", $params = array()){
if($controller === "index")
$controller = "home";
$controller = IoC::resolve('controller: shop', array($controller, $identifier));
return $controller;
});
shop base-controller located at application/libraries/controllers/shop.php
<?php
namespace Controllers;
use Base_Controller;
/**
* Shop controller
*/
class Shop extends Base_Controller
{
public function __construct($identifier){
/**
* #todo: load the shop model using the identifier
* possibly move this after the parent::__construct()
*/
parent::__construct();
}
}
file: applications/controllers/shops/home.php
<?php
/**
* #heads up: Shop_Controller is aliased in application/config/application.php
*/
class Shops_Home_Controller extends Shop_Controller
{
public function get_index(){
return ('test');
}
}
Problems:
when defining my routes for these nested shops controllers. Do i simply return the controller laravel should use to resolve the request, or do i trigger the action myself in the callback function in that route definition?
controllers aren't autoloading (when trying the implementation above), yet i'm using the correct conventions for those controllers (unless i'm missing something :-) ). I'm guessing this is because i'm using IoC, how do i cleanly implement this or what is my mistake?
how do i trigger the correct action? It should, as expected, trigger the corresponding HTTP-verb action, since my nested controllers are also RESTFUL-controllers.
extra question to keep things as clean as possible: 'index' defaults to home controller when not using IoC functionality. Is my solution (if-condition in routes.php) to mimic this functionality a clean one? or is there any better approach?
By all means:
If my approach is way off, please tell me, i'm a newbie at laravel, and it's the first framework i'm using, so i'm a newbie at frameworks in general.
I'd also like to apologize if my question isn't explained to well so feel free to ask extra info.
I tried my best at googling this problem, but couldn't find anything similar, which is a first, since all my other laravel problems were easily solved using google.
I'd kindly thank anyone taking the time to read this and even better send me in the right direction!
Ok, final solution, this is far from clean if you ask me, but it seems to work, at least as far as i've checked.
I'm also not to sure if there is an alternative, but due to lack of response and timepressure, i decided to go with this and keep fingers crossed :(.
//start.php
IoC::register('controller: shop', function($id, $controllerName){
//controller name is the name of the controller located in the shops map
$class = "Shops_" . ucfirst($controllerName) . "_Controller";
include(path('app') . 'controllers/shops/' . strtolower($controllerName) . '.php');
return new $class($id);
});
//routes.php
Route::any("shops/(:any)/(:any?)/(:any?)/(:all?)", function($id, $controller = "index", $action = "index", $params = ""){
if($controller === "index")
$controller = "home";
$params = explode('/', $params);
$controller = IoC::resolve("controller: shop", array($id, $controller));
$http_verb = Request::method();
/**
* Need to return this, and i now need to manually return every response in every action in every shop controller
*/
return call_user_func_array(array($controller, $http_verb . '_' . $action), $params);
});
so example given
class Shops_Home_Controller extends Shop_Controller
{
public function get_index(){
/**
* this works when doing things the usual way, but will not return any output
* when working with nested dependency injection
*/
$this->layout->nest('content', 'shops.index');
}
public function get_test(){
/**
* this needs to return layout object if it is to work with the nested dependency injection
*/
$this->layout->nest('content', 'shops.index');
}
}

How can we support modular and testable patterns with ASP.NET MVC 4 and MEF 2?

We're trying to use MEF 2 with ASP.NET MVC 4 to support an extensible application. There are really 2 parts to this question (hope that's okay SO gods):
How do we use Microsoft.Composition and the MVC container code (MEF/MVC demo source) to replace Ninject as our DI for ICoreService, ICoreRepository, IUnitOfWork, and IDbContext?
It looks like we can't use both Ninject and the MVC container at the same time (I'm sure many are saying "duh"), so we'd like to go with MEF, if possible. I tried removing Ninject and setting [Export] attributes on each of the relevant implementations, spanning two assemblies in addition to the web project, but Save() failed to persist with no errors. I interpreted that as a singleton issue, but could not figure out how to sort it out (incl. [Shared]).
How do we load multiple assemblies dynamically at runtime?
I understand how to use CompositionContainer.AddAssemblies() to load specific DLLs, but for our application to be properly extensible, we require something more akin to how I (vaguely) understand catalogs in "full" MEF, which have been stripped out from the Microsoft.Composition package (I think?); to allow us to load all IPluggable (or whatever) assemblies, which will include their own UI, service, and repository layers and tie in to the Core service/repo too.
EDIT 1
A little more reading solved the first problem which was, indeed, a singleton issue. Attaching [Shared(Boundaries.HttpRequest)] to the CoreDbContext solved the persistence problem. When I tried simply [Shared], it expanded the 'singletonization' to the Application level (cross-request) and threw an exception saying that the edited object was already in the EF cache.
EDIT 2
I used the iterative assembly loading "meat" from Nick Blumhardt's answer below to update my Global.asax.cs code. The standard MEF 2 container from his code did not work in mine, probably because I'm using the MEF 2(?) MVC container. Summary: the code listed below now works as desired.
CoreDbContext.cs (Data.csproj)
[Export(typeof(IDbContext))]
[Shared(Boundaries.HttpRequest)]
public class CoreDbContext : IDbContext { ... }
CoreRepository.cs (Data.csproj)
[Export(typeof(IUnitOfWork))]
[Export(typeof(ICoreRepository))]
public class CoreRepository : ICoreRepository, IUnitOfWork
{
[ImportingConstructor]
public CoreRepository(IInsightDbContext context)
{
_context = context;
}
...
}
CoreService.cs (Services.csproj)
[Export(typeof(ICoreService))]
public class CoreService : ICoreService
{
[ImportingConstructor]
public CoreService(ICoreRepository repository, IUnitOfWork unitOfWork)
{
_repository = repository;
_unitOfWork = unitOfWork;
}
...
}
UserController.cs (Web.csproj)
public class UsersController : Controller
{
[ImportingConstructor]
public UsersController(ICoreService service)
{
_service = service;
}
...
}
Global.asax.cs (Web.csproj)
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
CompositionProvider.AddAssemblies(
typeof(ICoreRepository).Assembly,
typeof(ICoreService).Assembly,
);
// EDIT 2 --
// updated code to answer my 2nd question based on Nick Blumhardt's answer
foreach (var file in System.IO.Directory.GetFiles(Server.MapPath("Plugins"), "*.dll"))
{
try
{
var name = System.Reflection.AssemblyName.GetAssemblyName(file);
var assembly = System.Reflection.Assembly.Load(name);
CompositionProvider.AddAssembly(assembly);
}
catch
{
// You'll need to craft exception handling to
// your specific scenario.
}
}
}
}
If I understand you correctly, you're looking for code that will load all assemblies from a directory and load them into the container; here's a skeleton for doing that:
var config = new ContainerConfiguration();
foreach (var file in Directory.GetFiles(#".\Plugins", "*.dll"))
{
try
{
var name = AssemblyName.GetAssemblyName(file);
var assembly = Assembly.Load(name);
config.WithAssembly(assembly);
}
catch
{
// You'll need to craft exception handling to
// your specific scenario.
}
}
var container = config.CreateContainer();
// ...
Hammett discusses this scenario and shows a more complete version in F# here: http://hammett.castleproject.org/index.php/2011/12/a-decent-directorycatalog-implementation/
Note, this won't detect assemblies added to the directory after the application launches - Microsoft.Composition isn't intended for that kind of use, so if the set of plug-ins changes your best bet is to detect that with a directory watcher and prompt the user to restart the app. HTH!
MEF is not intended to be used as DI framework. Which means that you should separate your "plugins" (whatever they are) composition from your infrastructure dependencies, and implement the former via MEF and the latter via whatever DI framework you prefer.
I think there are a little misunderstandings on what MEF can and can't do.
Originally MEF was conceived as purely an extensibility architecture, but as the framework evolved up to its first release, it can be fully supported as a DI container also. MEF will handle dependency injection for you, and does so through it's ExportProvider architecture. It is also entirely possible to use other DI frameworks with MEF. So in reality there are a number of ways things could be achieved:
Build a NinjectExportProvider that you can plug into MEF, so when MEF is searching for available exports, it will be able to interrogate your Ninject container.
Use an implementation of the Common Services Locator pattern to bridge between MEF and Ninject or vice versa.
Because you are using MEF for the extensibility, you'll probably want to use the former, as this exposes your Ninject components to MEF, which in turn exposes them to your plugins.
The other thing to consider, which is a bit disappointing, is in reality there isn't a lot of room for automagically plugging in of features ala Wordpress on ASP.NET. ASP.NET is a compiled and managed environment, and because of that you either resort to late-binding by loading assemblies manually at runtime, or you restart the application to pick up the new plugins, which sort of defeats the object of being able to plug new extensions in through the application.
My advice, is plan your architecture to pick up any extensibility points as startup and assume that any core changes will require a deployment and application restart.
In terms of the direct questions asked:
The CompositionProvider accepts in instance of ContainerConfiguration which is used internally to create the CompositionContainer used by the provider. So you could use this as the point by which you customise how you want your container to be instantiated. The ContainerConfiguration supports a WithProvider method:
var configuration = new ContainerConfiguration().WithProvider(new NinjectExportDescriptorProvider(kernel));
CompositionProvider.SetConfiguration(configuration);
Where NinjectExportDescriptorProvider might be:
public class NinjectExportDescriptorProvider: ExportDescriptorProvider
{
private readonly IKernel _kernel;
public NinjectExportDescriptorProvider(IKernel kernel)
{
if (kernel == null) throw new ArgumentNullException("kernel");
_kernel = kernel;
}
public override IEnumerable<ExportDescriptorPromise> GetExportDescriptors(
CompositionContract contract, DependencyAccessor dependencyAccessor)
{
var type = contract.ContractType;
if (!_kernel.GetBindings(type).Any())
return NoExportDescriptors;
return new[] {
new ExportDescriptorPromise(
contract,
"Ninject Kernel",
true, // Hmmm... need to consider this, setting it to true will create it as a shared part, false as new instance each time,
NoDependencies,
_ => ExportDescriptor.Create((c, o) => _kernel.Get(type), NoMetadata)) };
}
}
}
Note: I have not tested this, this is all theory, and is based on the example AppSettingsExportDescriptorProvider at: http://mef.codeplex.com/wikipage?title=ProgrammingModelExtensions
It's different from using the standard ExportProvider, because using the CompostionProvider is built around lightweight composition. But essentially you're wrapping up access to your Ninject kernel and making it available to your CompositionContainer.
As with adding a specific new provider (see above), you can use the ContainerConfiguration to read the available assemblies, probably something like:
var configuration = new ContainerConfiguration().WithAssemblies(AppDomain.GetAssemblies())
Again, I haven't tested all of this, but I hope it at least points you in the right direction.

Spring .Net Configuration Fluently

I have the need to use Spring .Net in a project and am exploring configuration options. All I can find about config for Spring .Net is config file stuff. Does Spring support configuration in code? I have used Castle and Ninject, and both seem to offer this natively. I have found projects that claim to add support, but I dont want some knock off project that will die in 6 months. I have found references in blogs that seem to indicate Spring supports this but I cant find any documentation!!
Part 2 of this might be would you recommend Spring .Net over Windsor knowing it cant support fluent configuration? I know both are great IoC containers, but I have worked on projects that have massive config files for Spring configuration and I hate it.
No, the current version (1.3) of Spring.NET only supports XML configuration. There has been talk about supporting Code as Configuration in future versions, but this has not yet materialized.
In my opinion, Castle Windsor is far superior to Spring.NET. I can't think of a single feature of Spring.NET that Castle Windsor doesn't have. On the other hand, Castle Windsor has the following features that are not available in Spring.NET:
Code as Configuration
Convention-based configuration
More lifetimes
Custom lifetimes
Object graph decommissioning
Explicit mapping of interfaces/base classes to concrete types
Type-based resolution
Modular configuration (Installers)
Built-in support for Decorators
Typed Factories
There are probably other features I forgot about...
It appears I was a bit too quick on the trigger here, although to my defense, the Spring.NET documentation also states that there's only XML configuration in the current version.
However, it turns out that if for certain contexts, a very primitive API is available that enables you to configure a context without XML. Here's an example:
var context = new GenericApplicationContext();
context.RegisterObjectDefinition("EggYolk",
new RootObjectDefinition(typeof(EggYolk)));
context.RegisterObjectDefinition("OliveOil",
new RootObjectDefinition(typeof(OliveOil)));
context.RegisterObjectDefinition("Mayonnaise",
new RootObjectDefinition(typeof(Mayonnaise),
AutoWiringMode.AutoDetect));
Notice how this API very closely mirrors the XML configuration schema. Thus, you don't get any fluent API from the IObjectDefinitionRegistry interface, but at least there's an API which is decoupled from XML. Building a fluent API on top of this is at least theoretically possible.
You will find a fully working spring fluent API for spring.net on github:
https://github.com/thenapoleon/Fluent-API-for-Spring.Net
This API brings fluent configuration, and will soon support convention based configuration.
In answer to the first part of your question: the springsource team appears to be working on a code configuration project on github: https://github.com/SpringSource/spring-net-codeconfig. It was announced with (but not included in) the 1.3.1 (december 2010) release.
From the MovieFinder example:
[Configuration]
public class MovieFinderConfiguration
{
[Definition]
public virtual MovieLister MyMovieLister()
{
MovieLister movieLister = new MovieLister();
movieLister.MovieFinder = FileBasedMovieFinder();
return movieLister;
}
[Definition]
public virtual IMovieFinder FileBasedMovieFinder()
{
return new ColonDelimitedMovieFinder(new FileInfo("movies.txt"));
}
}
There is another option using the Spring.AutoRegistration. The same concept used with Unity AutoRegistration.
https://www.nuget.org/packages/Spring.AutoRegistration
http://autoregistration.codeplex.com/
var context = new GenericApplicationContext();
context.Configure()
.IncludeAssembly(x => x.FullName.StartsWith("Company.ApplicationXPTO"))
.Include(x => x.ImplementsITypeName(), Then.Register().UsingSingleton()
.InjectByProperty(If.DecoratedWith<InjectAttribute>))
.ApplyAutoRegistration();
It is also possible to use Spring.FluentContext project.
With it, the configuration of MovieFinder would look as follows:
// Configuration
private static IApplicationContext Configure()
{
var context = new FluentApplicationContext();
context.RegisterDefault<MovieLister>()
.BindProperty(l => l.MovieFinder).ToRegisteredDefaultOf<ColonDelimitedMovieFinder>();
context.RegisterDefault<ColonDelimitedMovieFinder>()
.UseConstructor((FileInfo fileInfo) => new ColonDelimitedMovieFinder(fileInfo))
.BindConstructorArg().ToValue(new FileInfo("movies.txt"));
return context;
}
// Usage
static void Main(string[] args)
{
IApplicationContext context = Configure();
var movieLister = context.GetObject<MovieLister>();
foreach (var movie in movieLister.MoviesDirectedBy("Roberto Benigni"))
Console.WriteLine(movie.Title);
Console.ReadLine();
}
It does not require any hardcoded literal ID for objects (but allows that), it is type safe and contains documentation with samples on GitHub wiki.
Using the Fluent-API-for-Spring.Net, the configuration could look something like:
private void ConfigureMovieFinder()
{
FluentApplicationContext.Clear();
FluentApplicationContext.Register<ColonDelimitedMovieFinder>("ColonDelimitedMovieFinder")
.BindConstructorArgument<FileInfo>().To(new FileInfo("movies.txt"));
// By default, fluent spring will create an identifier (Type.FullName) when using Register<T>()
FluentApplicationContext.Register<MovieLister>()
.Bind(x => x.MovieFinder).To<IMovieFinder>("ColonDelimitedMovieFinder");
}

Resources