IoC container that supports constructor injection with Scala named/default arguments? - scala

I would prefer using constructor injection over JavaBean property injection if I could utilize the named and default arguments feature of Scala 2.8. Any IoC-containers exists that supports that or could be easily extended to do so? (The required information is there on runtime in the scala.reflect.ScalaSignature annotation of the class.)
I also have some basic(?) expectations from the IoC container:
Auto-wiring (by target class/trait or annotation, both one-to-one and one-to-many)
Explicit injection (explicit wiring) without much hassle (like Guice is weak there). Like user is injected that way in new ConnectionPool(user="test").
Life-cycle callback for cleanup on shutdown (in the proper order)
Spring can do these, obviosuly, but it doesn't support named parameters. I have considered using FactoryBean-s to bridge Scala and Spring, but that would mean too much hassle (boilerplate or code generation), as far as I see.

PART A
I have a work-in-progress reflection library that parses the Scala signature and is currently able to resolve named parameters: https://github.com/scalaj/scalaj-reflect
Unfortunately, I haven't yet tied it back into Java reflection to be able to invoke methods, nor have I added the logic to resolve default values (though this should be trivial). Both features are very high on my to-do list :)
This isn't an IoC container per-se, but it's a pre-requisite for another project of mine: https://github.com/scalaj/scalaj-spring. Work on scalaj-spring stopped when it became blindingly obvious that I wouldn't be able to make any worthwhile further progress until I had signature-based reflection in place.
PART B
All of that stuff is intended for big enterprisey people anyway. Those with no choice but to integrate their shiny new Scala code into some hulking legacy system... If that's not your use case, then you can just do Scala DI directly inside Scala.
There's DI support provided under the Lift banner: http://www.assembla.com/wiki/show/liftweb/Dependency_Injection
You should also hunt around for references to the cake pattern

Another dependency injection framework in Scala is subcut

I have considered using FactoryBean-s to bridge Scala and Spring, but that would mean too much hassle
I am not sure I understand the complexity. Its actually quite simple to implement Spring FactoryBeans in Scala. Check this little write-up http://olegzk.blogspot.com/2011/07/implementing-springs-factorybean-in.html

I've just released Sindi, an IoC container for the Scala programming language.
http://aloiscochard.github.com/sindi/

Related

What's the scala alternative to runtime-preserved annotations

I just realized I cannot have annotations in scala, that are preserved and analyzed at runtime. I also checked this question, but I didn't quite get it what are the alternatives.
DI - an answer mentions that there is no need for DI framework in scala. While that might be the case on a basic level (although I didn't quite like that example; what's the idiomatic way of handling DI?), Java DI frameworks like spring are pretty advanced and handle many things like scheduled jobs, caching, managed persistence, etc, all through annotations, and sometimes - custom ones.
ORM - I'll admit I haven't tried any native scala ORM, but from what I see in squeryl, it also makes some use of annotations, meaning they are unavoidable?
any serialization tool - how do you idiomatically customize serialization output to JSON/XML/...?
Web service frameworks - how do you define (in code) the mappings, headers, etc. for RESTful or SOAP services?
Scala users need to have a hybrid scala/java (for the annotations) project in order to use these facilities that are coming from Java?
And are the native scala alternatives for meta-data nicer than annotations? I'm not yet fully into the scala mode of thinking, and therefore most of the examples look ugly to me, compared to using annotations, so please try to be extra convincing :)
Actually, Scala does have runtime-retained annotations. The difference is that they are not stored as Java annotations but are instead encoded inside the contents of binary ScalaSignature annotation (which, by itself, is a runtime-retained Java annotation).
So, Scala annotations can be retrieved at runtime, but instead of using Java reflection, one must use Scala reflection:
class Awesome extends StaticAnnotation
#Awesome
class AwesomeClass
import scala.reflect.runtime.universe._
val clazz = classOf[AwesomeClass]
val mirror = runtimeMirror(clazz.getClassLoader)
val symbol = mirror.classSymbol(clazz)
println(symbol.annotations) // prints 'List(Awesome)'
Unfortunately, Scala reflection is still marked as experimental and is actually unstable at this point (SI-6240 or SI-6826 are examples of quite serious issues). Nevertheless, it seems like the most straightforward replacement for Java reflection and annotations in the long term.
As for now, one has to use Java annotations which I think is still a nice solution.
Regarding frameworks and libraries for DI/ORM/WS/serialization - Scala still doesn't seem to be mature in this area, at least not as Java is. There are plenty of ongoing projects targeting these problems, some of them are already really nice, others are still in development. To name a few that come to my mind: Squeryl, Slick, Spray, Pickling.
Also, Scala has some advanced features that often make annotations unneccessary. Typeclasses (implemented with implicit parameters) are probably good example of that.

Avoid namespace conflicts in Java MPI-Bindings

I am using the MPJ-api for my current project. The two implementations I am using are MPJ-express and Fast-MPJ. However, since they both implement the same API, namely the MPJ-API, I cannot simultaneously support both implementations due to name-space collisions.
Is there any way to wrap two different libraries with the same package and class-names such that both can be supported at the same time in Java or Scala?
So far, the only way I can think of is to move the module into separate projects, but I am not sure this would be the way to go.
If your code use only a subset of MPI functions (like most of the MPI code I've reviewed), you can write an abstraction layer (traits or even Cake-Pattern) which defines the ops your are actually using. You can then implement a concrete adapter for each implementation.
This approach will also work with non-MPI communication layers (think Akka, JGroups, etc.)
As a bonus point, you could use the SLF4J approach: the correct implementation is chosen at runtime according to what's actually in the classpath.

Why do web development frameworks tend to work around the static features of languages?

I was a little surprised when I started using Lift how heavily it uses reflection (or appears to), it was a little unexpected in a statically-typed functional language. My experience with JSP was similar.
I'm pretty new to web development, so I don't really know how these tools work, but I'm wondering,
What aspects of web development encourage using reflection?
Are there any tools (in statically typed languages) that handle (1) referring to code from a template page (2) object-relational mapping, in a way that does not use reflection?
Please see lift source. It doesn't use reflection for most of the code that I have studied. Almost everything is statically typed. If you are referring to lift views they are processed as Xml nodes, that too is not reflection.
Specifically referring to the <lift:Foo.bar/> issue:
When <lift:Foo.bar/> is encountered in the code, Lift makes a few guesses, how the original name should have been (different naming conventions) and then calls java.lang.Class.forName to get the class. (Relevant code in LiftSession.scala and ClassHelpers.scala.) It will only find classes registered with addToPackages during boot.
Note that it is also possible (and common) to register classes and methods manually. Convention is still that all transformations must be of the form NodeSeq => NodeSeq because that is the only thing which makes sense for an untyped HTML/XHTML output.
So, what you have is Lift‘s internal registry of node transformations on one side, and on the other side the implicit registry of the module. Both types use a simple string lookup to execute a method. I guess it is arguable if one is more reflection based than the other.

How would one do dependency injection in scala?

I'm still at the beginning in learning scala in addition to java and i didn't get it how is one supposed to do DI there? can or should i use an existing DI library, should it be done manually or is there another way?
Standard Java DI frameworks will usually work with Scala, but you can also use language constructs to achieve the same effect without external dependencies.
A new dependency injection library specifically for Scala is Dick Wall's SubCut.
Whereas the Jonas Bonér article referenced in Dan Story's answer emphasizes compile-time bound instances and static injection (via mix-ins), SubCut is based on runtime initialization of immutable modules, and dynamic injection by querying the bound modules by type, string names, or scala.Symbol names.
You can read more about the comparison with the Cake pattern in the GettingStarted document.
Dependency Injection itself can be done without any tool, framework or container support. You only need to remove news from your code and move them to constructors. The one tedious part that remains is wiring the objects at "the end of the world", where containers help a lot.
Though with Scala's 2.10 macros, you can generate the wiring code at compile-time and have auto-wiring and type-safety.
See the Dependency Injection in Scala Guide
A recent project illustrates a DI based purely on constructor injection: zalando/grafter
What's wrong with constructor injection again?
There are many libraries or approaches for doing dependency injection in Scala. Grafter goes back to the fundamentals of dependency injection by just using constructor injection: no reflection, no xml, no annotations, no inheritance or self-types.
Then, Grafter add to constructor injection just the necessary support to:
instantiate a component-based application from a configuration
fine-tune the wiring (create singletons)
test the application by replacing components
start / stop the application
Grafter is targeting every possible application because it focuses on associating just 3 ideas:
case classes and interfaces for components
Reader instances and shapeless for the configuration
tree rewriting and kiama for everything else!
I haven't done so myself, but most DI frameworks work at the bytecode level (AFAIK), so it should be possible to use them with any JVM language.
Previous posts covered the techniques. I wanted to add a link to Martin Odersky's May 2014 talk on the Scala language objectives. He identifies languages that "require" a DI container to inject dependencies as poorly implemented. I agree with this personally, but it is only an opinion. It does seem to indicate that including a DI dependency in your Scala project is non-idiomatic, but again this is opinion. Practically speaking, even with a language designed to inject dependencies natively, there is a certain amount of consistency gained by using a container. It is worth considering both points of view for your purposes.
https://youtu.be/ecekSCX3B4Q?t=1154
I would suggest you to try distage (disclaimer: I'm the author).
It allows you to do much more than a typical DI does and has many unique traits:
distage supports multiple configurations (e.g. you may run your app
with different sets of component implementations),
distage allows you to correctly share dependencies across your tests
and easily run same tests for different implementations of your
components,
distage supports roles so you may run multiple services within the same process sharing dependencies between them,
distage does not depend on scala-reflect
(but supports all the necessary features of Scala typesystem, like
higher-kinded types).
You may also watch our talk at Functional Scala 2019 where we've discussed and demonstrated some important capabiliteis of distage.
I have shown how I created a very simple functional DI container in scala using 2.10 here.
In addition to the answer of Dan Story, I blogged about a DI variant that also uses language constructs only but is not mentioned in Jonas's post: Value Injection on Traits (linking to web.archive.org now).
This pattern is working very well for me.

Is it possible to use C# Object Initializers with Factories [duplicate]

This question already has answers here:
Is it possible to use a c# object initializer with a factory method?
(7 answers)
Closed 9 years ago.
I'm looking at the new object initializers in C# 3.0 and would like to use them. However, I can't see how to use them with something like Microsoft Unity. I'm probably missing something but if I want to keep strongly typed property names then I'm not sure I can. e.g. I can do this (pseudo code)
Dictionary<string,object> parms = new Dictionary<string,object>();
parms.Add("Id", "100");
IThing thing = Factory.Create<IThing>(parms)();
and then do something in Create via reflection to initialise the parms... but if I want it strongly typed at the Create level, like the new object intitalisers then I don't see how I can.
Is there a better way?
Thanks
AFAIK, it's not possible to do. I would stay away from reflection in this case if I were you, as reflection is really really slow and could become easily a bottleneck in your application. I think using reflection for this is actually abusing reflection.
Do not shoot yourself in the leg because you want to emulate some syntactic sugar. Just set the fields / properties of the instance one by one, the classic way. It will be much faster than reflection.
Remember: No design pattern is silver bullet. Factory methods and object initializers are nice but try to use common sense and only use them when they actually make sense.
I'm not that familiar with Unity, but the idea behind IoC/DI is that you do not construct object yourself, so of course you can't use object initializer syntax.
I guess what you could use from C# 3.0 in your example is an anonymous type instead of Dictionary. No idea if Unity can consume that.
Anyway, if you make those calls like Factory.Create() you are probably using IoC in a wrong way.
Consider investing the time in leaning Unity or Castle or any of the other IOC frameworks available for .net. The IOC will let you transfer the complexity of object initialization from your code to a configuration file. In your application you will use interfaces to access the objects initialize in by the IOC container. The other service the IOC gives you is control of the lifetime of the objects (singletons, etc).
Graham, the idea behind IoC/DI is that your components declare their dependencies as either constructor parameters or public properties of specific types (usually interfaces).
The container then builds a dependency graph and satisfies those (with regards to component lifestyle if case of mature IoC's like Castle Windsor).
So basically you write your components, state dependencies and then register contracts and implementations in IoC container and don't care about constructing objects anymore. You just make a single call similar to Application.Start() :)
The bad thing is that some frameworks are hard to integrate with. Like ASP.NET WebForms, where you don't have control over IHttpHandler creation and cannot setup factories that would use IoC to instantiate those. You can check Ayende's "Rhino Igloo" which does it's best to use IoC in an environment like this.
Maybe this can help... Have you checked out this blog post?
http://www.cookcomputing.com/blog/archives/000578.html
The author presents a method for building an object from a factory and registering the object in the IoC container.
This is answered better in this question: Is it possible to use a c# object initializer with a factory method?.
There were four possibilities:
Accept a lambda as an argument
Return a builder instead
Use a default constructor, passing in an initialized object
Use an anonymous object