What is equivalent of RegisterInstance<Interface>(new Class()) design time? - unity-container

I am trying to implement design time Unity configuration (e.g.: using app.config). I am struggling with the very example of how to use the tag the "configuring instances" section.
Their sample of run-time configuration is:
EmailService myEmailService = new EmailService();
myContainer.RegisterInstance<IMyService>(myEmailService);
but no equivalent design-time configuration given. If I do:
<container>
<instance type="IMyService" value="EmailService" />
</container>
I will naturally get a "TypeConverter cannot convert from System.String" exception. Am I supposed to create some sort of type converter merely so that I could declare an instance? Is there an easier way?

Related

Where to put entity 'helper functions'?

I am having trouble understand a key concept of Symfony 2.
I am working on a website where users can create content which then can be sent to other people, using a secret url. Something like www.yoursite.com/{secret-identifier-string}.
I plan on doing this as follows:
Persist the user's content.
Create the identifier string containing the content id and the creation timestamp (or any other content which will never change again, as extra safety feature) with a two-way encryption method (like mcrypt_encrypt).
Create the link and display it to the user to give it away
Whenever a url is called, the identifier string will be decrypted. If the provided timestamp matches the corresponding value of the content id row, the page will be displayed.
My questions are:
Would you consider this a good procedure in general?
Outside Symfony2 I would create helper methods like getIdentifierString() and getContentPageLink(). Where do I put the corresponding code in Symfony2? Does it belong inside the entity class? If so I am having problems because I am using a service class for encryption. The service is only available in the controller.
Thanks a lot!
With all due respect to DI and service oriented design, namespacing and all the good stuff we benefit from,
I still refuse to type or read:
$this->mysyperfancyservice->dowhatevertheseviceissupposedtodowith($the_entity);
where a simple
do($the_entity);
is all I need on 150 instances across my project, where do is something everyone working on the project will know about.
That is what helper is meant for - readability and simplicity. As long as it doesn't depend on other services though.
My solution for that is in basic Composer feature:
"autoload": {
...
"files": [ "src/helper/functions.php" ]
}
I put a very limited number of extremely useful functions in src/helper/functions.php file, and add it to project like that.
In order for the function to become available project-wide, it is required to run:
composer dump-autoload
The general idea is that you create "helper classes" rather than "helper functions". Those classes may have dependencies on other classes in which case you'll define them as a service.
It sounds like your methods do have dependencies (on encryption) so you can make a new service that is responsible for generating links. In it's constructor it would take the encryptor and the methods would be passed the entity to generate a link/string for.
for example, your service:
<service id="app_core.linkifier" class="App\CoreBundle\Linkifier">
<argument type="service" id="the.id.for.encryptor"/>
</service>
and class:
class Linkifier
{
private $encryptor;
public function __construct(Encryptor $encryptor)
{
$this->encryptor = $encryptor;
}
public function generateContentPageLink(Entity $the_entity)
{
return $this->encryptor->encrypt($the_entity);
}
}

Is it possible to place custom values (properties) in ejb-jar.xml?

1) We are using OpenEJB (both embedded and standalone) with a few deployed EJBs. We would like to specify some simple static business rules and values (example: icon_size=200). Normally, we would put them in a regular properties file (example: rules.properties). Since we shouldn't access the file system directly while inside the application server, is is possible to place those key-value pairs somewhere inside the ejb-jar.xml?
2) If not, is there a standard mechanism to do this? What is it?
Thanks
Use env-entry. In XML:
<env-entry>
<env-entry-name>icon_size</env-entry-name>
<env-entry-type>java.lang.Integer</env-entry-type>
<env-entry-value>200</env-entry-value>
</env-entry>
In annotation:
#Resource(name="icon_size")
int icon_size;
I personally just use a .properties file; well a TernarySearchTree which reads in .properties and .XML files and allows quick retrieval. These files are available at application level. However you can in EJB 3 inject env-entry elements into your EJB. This link explains it in good detail Injection of env entry
There are some OpenEJB extensions here that might be useful.
env-entries.properties
Check out the Custom Injection example which is basically allows the <env-entry> to be specified as plain properties in a META-INF/env-entries.properties file. Nice for collapsing all those name & value pairs into a simple properties file. Internally, we just generate the xml for you using those properties. The default type is always java.lang.String, which is good for this next part.
java.beans.PropertyEditor support
Any <env-entry> which is of <env-entry-type> java.lang.String will automatically have its type converted using the VM java.beans.PropertyEditor for the target type. That's also how Spring does the converting. There are few built-in converters, such as #Resource java.util.Date myDate and #Resource java.io.File myFile

GenericSetup: What does toolset.xml accomplish if ToolInit still has to be called from initialize()

It seems that toolset.xml goes only half way. Ideally it should be able to do away with the ToolInit call in initialize() in __init__.py. But I could not get the tool icon to show in the ZMI without the ToolInit call.
The ToolInit call in the initialize function registers the tool class as something that can be added to OFS based folders in the database - primarily it register a factory for creating instances of the class. This is basically the same that ContentInit does for normal content classes.
Once the class is registered and its meta_type is known, instances of the class can be added to OFS based Folders. GenericSetup steps are responsible for managing persistent content and can be used to add tool instances to the database.
If we wanted to avoid the code in the initialize function, we would need to create some custom ZCML directives instead and use these in a configure.zcml to register the type and its factory. Dexterity has gone this route, but its not available for Archetypes based content types or general classes like tools.
The goal of toolset.xml is to instantiate tools into the database. It can also be used to remove tools; this is very useful in upgrade steps for example.
Example toolset.xml:
<?xml version="1.0"?>
<tool-setup>
<required tool_id="portal_foo" class="dotted.path.to.FooTool" />
<forbidden tool_id="portal_spam" />
</tool-setup>
This example toolset.xml would instantiate the FooTool class as portal_foo in it's context, and remove any object with id portal_spam if present.
Note that you can use a toolset.xml in any GenericSetup profile, not just in the package that defines the tool in the first place, for example, in general policy packages for a site you develop.

How to conditionally bind a instance depending on the injected type using unity?

I'm used to Ninject, and for a specific project I'm asked to learn Unity.
There is one thing i can't find information on how to do.
In Ninject I can state:
Bind<IWarrior>().To<Samurai>().Named("Samurai");
Bind<IWarrior>().To<Ninja>().Named("Ninja");
Bind<IWeapon>().To<Katana>().WhenInjectedInto(typeof(Samurai));
Bind<IWeapon>().To<Shuriken>().WhenInjectedInto(typeof(Ninja));
And then when one asks for the warrior named samurai, the samurai comes with kanana and the ninja comes with shurikens. As it should.
I don't want to reference the container in the warriors to get the appropriate weapon, and don't want to contaminate the model with attributes (is in another assembly that doesn't have reference to ninject or unity)
PD: I'm looking for a code way, not via xml config.
This should work with Unity:
Container
.Register<IWeapon, Katana>("Katana")
.Register<IWeapon, Shuriken>("Shuriken")
.Register<IWarrior, Samurai>("Samurai", new InjectionConstructor(new ResolvedParameter<IWeapon>("Katana"))
.Register<IWarrior, Ninja>("Ninja", new InjectionConstructor(new ResolvedParameter<IWeapon>("Shuriken")));
Test:
var samurai = Container.Resolve<IWarrior>("Samurai");
Assert.IsTrue(samurai is Samurai);
Assert.IsTrue(samurai.Weapon is Katana);
var ninja = Container.Resolve<IWarrior>("Ninja");
Assert.IsTrue(ninja is Ninja);
Assert.IsTrue(ninja.Weapon is Shuriken);

how can i use structure map asp.net 3.5

I am new to the structure map but i want to use it in my asp.net site for dependency injection
can any one suggest me simple example to use structure map for the dependency injection
you will need to do something like this:-
StructureMapConfiguration
.ForRequestedType<IResourceA>()
.TheDefaultIsConcreteType<ResourceB>()
.CacheBy(InstanceScope.Singleton);
This tells StructureMap to inject ResourceB when there is a request for ResourceA.
Structure Map
You can configure programatically or via configuration file.
Programatical example (there are other ways):
StructureMap.StructureMapConfiguration.ForRequestedType<ISomething>().TheDefaultIsConcreteType<ConcreteSomething>();
then you can get an instance of the configured type using this sort of code:
//The concrete type will be ConcreteSomething
ISomething instance = ObjectFactory.GetInstance<ISomething>();
You can do it in a config file:
<StructureMap MementoStyle="Attribute">
<DefaultInstance PluginType="Blah.ISomething, Blah.SomethingDLL" PluggedType="Blah.Concrete.ConcreteSomething,Blah.ConcreteDLL"/>
</StructureMap>
and in the main method or Global.asax you can set this config by saying:
StructureMap.ObjectFactory.Initialize(x => { x.PullConfigurationFromAppConfig = true; });
and use it the same way as above:
ISomething instance = ObjectFactory.GetInstance<ISomething>();
If the concrete class has a constructor that needs instances injected in it, and you have those configured, the concrete types will get injected by the framework.
There are ways of passing parameters to constructors, dealing with Gereric types, creating named instances that are configured with specific constructor/property values. I use this framework and like it very much.

Resources