Dependency injection with Akka - scala

I use Guice in my application quite a lot. Recently i start to learn akka actors and felt like refactoring my application with it.
However upfront i am already wondering how all my guice will work with actors. I went on searching on google and it is kinda a bit messy.
The most up to date docs that i have found on the subject are theses:
http://letitcrash.com/post/55958814293/akka-dependency-injection
http://eng.42go.com/tag/guice/
which do not advocate same thing.
I must confess i still need to read a lot, i am at the beginning of learning akka. I Did few examples and red few things, but i don't want to go to deep into something to realize later that i will have many problems.
So my question is as of today, what is the consensus on how to use Akka Actors with dependency injection.
What kind of injection is possible ? Can we wire actors with object/other actors/....
Can anyway please outline in a concise way something that can help me to understand what is possible and what is the best practices ?

I know you are working in Akka with Guice and Scala, but Typesafe provides a tutorial describing how things work in Akka with Spring and Java. This can provide a good starting point for understanding how dependency injection fits into the Actor lifecycle for your situation.
Meanwhile, here is some sample code from their documentation for using a factory method to inject constructor arguments:
class DependencyInjector(applicationContext: AnyRef, beanName: String) extends IndirectActorProducer {
override def actorClass = classOf[Actor]
override def produce = // obtain fresh Actor instance from DI framework ...
}
val actorRef = system.actorOf(Props(classOf[DependencyInjector], applicationContext, "hello"), "helloBean")
Here are some guidelines compiled by Typesafe on the matter.
Finally, note the following from the documentation:
"When using a dependency injection framework, actor beans MUST NOT have singleton scope."

The latest activator has a tutorial for Akka with Guice.

Related

Static method and constructor interception mocking in Scala/Spark

All, Here is a problem that my searches have yielded little insight into. I think this should be a fairly common problem for all of us developing against big data frameworks but also seek 100% test coverage. So I will post the question here in an attempt to gather the best community response & ideas.
Consider the scenario where we need to mock a class that instantiate an external API object
class SolrClientWrapper {
def doWork() = {
val cli = new CloudSolrClient("zkHost1")
???
}
}
To get 100% test coverage, and without actually relying on the Solr server to be up at all times during unit testing, we shall have a way to intercept the call to new CloudSolrClient. As far as I know, the ONLY library available is PowerMock
Here is The Twist
PowerMock and other Mock libraries require asm as a dependency, but a complex framework Spark project also require asm. There are version conflicts and thus (test-)runtime hell.
What is the best design refactor/libraries for this situation?
Instead of creating a new CloudSolrClient object within the SolrClientWrapper class, it should be passed as a dependency. Then in your test you can pass a mock instead of the real object. Note that there are many dependency injection frameworks and mechanisms that can make it easier for you to manage your dependencies (e.g. to automatically instantiate them and pass to the constructor for you).
Not sure what asm is, but the code you posted should be easily testable without such dependencies once you remove parts of the code that instantiate stuff inside the class body (and thus the need to "intercept" anything).

How to use scala actor based event sourcing app from another language (python)

I'm somewhat familiar with scala and less familiar with akka, although I know what actor models is (the idea seems quite simple).
So let's say that right now this is my code (in reality what I need is event sourcing application). I need to be able to use it from any language, not just from JVM.
So of course I googled about that and I've found this. The problem with that is that If my understanding is correct I would need to create some custom protocol, deserialization and dispatching for zmq messages and that is totally uncool. Maybe there exists solution for that already? If not, than how to do that in most efficient way? Maybe I need to create some message case classes and something like facade actor that would do deserialization?
class HelloActor extends Actor {
def receive = {
case "hello" => println("well, helllo!")
case _ => println("huh?")
}
}
object Main extends App {
val system = ActorSystem("HelloSystem")
val helloActor = system.actorOf(Props[HelloActor], name = "helloactor")
helloActor ! "hello"
helloActor ! "buenos dias"
}
There are many ways to do this, depends on the protocol you are using ect. For a language specific way is you can use Pyro. Just like java, you can serialize generic objects in python and then transfer them over the network, which you can use Pyro for. You can take advantage of the fact that python is implemented on both the jvm (Jython), and natively. Not sure if its a great idea to write this just in scala and python, I would create the API in java, and then add that to the scala classpath, then any other JVM language can also use your API. In addition it's more common to use jython with java so there are other benifits that come with being the majority.
But anway the common language that the jvm and python will understand will be these serialized python objects. So what you will need to know is:
How to use jython with java
How to use pyro
And yea using scala with jython is only a matter of adding the jars to the classpath, as you probably already know.
EDIT: Ok I think I might not have made this method clear enough. So basically:
JVM uses jython to create a jython instance, which is sent to a remote python object. The communication is done with the module Pyro. This program can send serialized python objects back as well.
This is what happens normally with remote actors in java, except the messages are implementing Serializable. Python and Java are not in the same process, or using native methods, or anything like that. They can be on the same machine or different machines. This method is not platform specific.
Hopefully this method is usefull to someone.
In my case the Akka actor solution was a little bit overkill, so I end up implementing my own event sourcing solution in this open source project.
The persistence layer is a decision for the developer, but I provide practical examples of execution using couchbase.
Take a look in case you consider useful.
https://github.com/politrons/Scalaydrated

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.

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

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/

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.