Pick a dependency by key/name when registering via RegisterType() or RegisterAssemblyTypes()? - autofac

In a scenario where I'm using Autofac with TypedNamedAndKeyedServices, Is there a way when using RegisterType() or RegisterAssemblyTypes() to register a type (which uses refection to find the appropriate constructor), to specify that one of its dependencies uses a keyed/named service? Ideally I'd like to do something like this:
builder.RegisterType<ServiceA>();
...
public class ServiceA
{
public ServiceA([ByName("online")] IDependencyB dependencyB, ...)
{ ... }
}
If not, then how about adding it to Autofac:
How complicated would it be to implement? (I've only looked at the Autofac source very superficially.)
Is specifying a dependency like this a good design? Is there a better way?
Would that be a useful feature for anyone else?

Not as discoverable as I'd like, but:
builder.RegisterType<ServiceA>()
.WithParameter(
(pi, c) => pi.Name == "dependencyB",
(pi, c) => c.ResolveNamed<IDependencyB>("online"));
We've looked at simplifications in the past, butthe number of variations on this scenario is quite large. This approach covers all of them using mostly familiar APIs (System.Reflection and 'Resolve...()'.)

Related

Cannot mock the RedisClient class - method pipeline overrides nothing

I have a CacheService class that uses an instance of the scala-redis library
class CacheService(redisClient: RedisClient) extend HealthCheck {
private val client = redisClient
override def health: Future[ServiceHealth] = {
client.info
...
}
In my unit test, I'm mocking the client instance and testing the service
class CacheServiceSpec extends AsyncFlatSpec with AsyncMockFactory {
val clientMock = mock[RedisClient]
val service = new CacheService(clientMock)
"A cache service" must "return a successful future when healthy" in {
(clientMock.info _).expects().returns(Option("blah"))
service.health map {
health => assert(health.status == ServiceStatus.Running)
}
}
}
yet I'm getting this compilation error
Error:(10, 24) method pipeline overrides nothing.
Note: the super classes of <$anon: com.redis.RedisClient> contain the following, non final members named pipeline:
def pipeline(f: PipelineClient => Any): Option[List[Any]]
val clientMock = mock[RedisClient]
My research so far indicates ScalaMock 4 is NOT capable of mocking companion objects. The author suggests refactoring the code with Dependency Injection.
Am I doing DI correctly (I chose constructor args injection since our codebase is still relatively small and straightforward)? Seems like the author is suggesting putting a wrapper over the client instance. If so, I'm looking for an idiomatic approach.
Should I bother with swapping out for another redis library? The libraries being actively maintained, per redis.io's suggestion, use companion objects as well. I personally think this is is not a problem of these libraries.
I'd appreciate any further recommendations. My goal here is to create a health check for our external services (redis, postgres database, emailing and more) that is at least testable. Criticism is welcomed since I'm still new to the Scala ecosystem.
Am I doing DI correctly (I chose constructor args injection since our
codebase is still relatively small and straightforward)? Seems like
the author is suggesting putting a wrapper over the client instance.
If so, I'm looking for an idiomatic approach.
Yes, you are right and this seems to be a known issue(link1). Ideally, there needs to a wrapper around the client instance. One approach could be to create a trait that has a method say connect and extend it to RedisCacheDao and implement the connect method to give you the client instance whenever you require. Then, all you have to do is to mock this connection interface and you will be able to test.
Another approach could be to use embedded redis for unit testing though usually, it is used for integration testing.You can start a simple redis server where the tests are running via code and close it once the testing is done.
Should I bother with swapping out for another redis library? The
libraries being actively maintained, per redis.io's suggestion, use
companion objects as well. I personally think this is is not a problem
of these libraries.
You can certainly do that. I would prefer Jedis as it is easy and it's performance is better than scala-redis(while performing mget).
Let me know if it helps!!

Readonly lens for a function

I have a case class like:
case class Person(name, birthDate, many other fields) { def something = //compute it from the fields }
What i would really like in the end is to have lenses for name, birthDate, and a readonly lens for something, and if possible compose them together to have a single lens for setting name/birthDate and reading name/birthDate/something
From my limited knowledge it does not seem possible (in shapeless i get an error when creating lens for the something function)
Maybe it's possible in other lens libraries or maybe there's a refactor i need to do
Considering that optics in general solve the issue of two-way access (getting/settings something if possible), there is no such thing as read only lenses.
So, whether you use shapeless or Monocle or something else you cannot do it this way.
However, nothing stops you from doing:
// updates person
(lens1 composeLens lens2 composeLens personLens).modify(...)
// gets Person and reads "read only" property
(lens1 composeLens lens2 composeLens personLens).get(object).something
About optics in general there is a nice article about them and how you can use them with Monocles.
EDIT. Well, perhaps you could design something to have "read only" optics - that is Prism which always fails to update, but that would be a terrible abomination of the idea I believe. Then you would not work on Person but on some coproduct of Person, but that would be awkwardly counter intuitive, so I do not even start to think how could it be implemented.

What are configurations in Gradle?

When working with dependency resolution in gradle, you usually see something like this:
configurations {
optional
compile
runtime.extendsFrom compile
testCompile.extendsFrom runtime
}
and I wanted to know of what type is optional or compile? Is it a Class? a string? what methods can I call for it?
Besides all this, is there a way to find out these things automatically, similar to ctrl+space when on something in eclipse?
They are classes that implements org.gradle.api.artifacts.Configuration. The Gradle DSL doc also contains more information about the configuration DSL core type.
To find out more info about internal classes etc, which is useful when for instance looking up classes and methods in the Gradle javadoc, it is often as simple as just printing out the class names. Quite often though, you will end up with some internal implementing class instead of the API interface you're interested in, but regardless of that it's a way get started on what to search for. I tend to keep the source code of all open source projects we're using available in the IDE. That way it's easy to jump into the correct class (even when it's not available through context shortcuts) and look around.
To get more information about configurations in your case, you could add a task that simply prints out the relevant info. E.g. something like:
task configInfo << {
println "configurations.class: ${configurations.class}"
println "configurations.compile class: ${configurations.compile.class}"
println "implements ${Configuration} interface? ${configurations.compile instanceof Configuration}"
}
which in my case results in the following output
$ gradle configInfo
:configInfo
configurations.class: class org.gradle.api.internal.artifacts.configurations.DefaultConfigurationContainer_Decorated
configurations.compile class: class org.gradle.api.internal.artifacts.configurations.DefaultConfiguration_Decorated
implements interface org.gradle.api.artifacts.Configuration interface? true
I am no Gradle expert, but this seems like a simple getter delegated to another object in a DSL fashion. You could write the same with something like this:
class MyDsl {
def config = [:].withDefault { false }
void configure(closure) {
closure.delegate = this
closure()
}
def getOptional() { config.optional = true }
def getCompile() { config.compile = true }
def getTest() { config.test = true }
}
dsl = new MyDsl()
dsl.configure {
optional
compile
}
dsl.config.with {
assert optional
assert compile
assert !test
}
You could return some specific object to pass to runtime.extendsFrom() method.
For auto-complete, IIRC that's what groovy-eclipse DSLD (DSL descriptors) are for. You may want to give a try to this gradle DSLD which is in eclipse-integration-gradle plugin.
As per this ticket it has been done long ago.
The question "what type is optional or compile" isn't really valid. That is kind of like asking what type does "instanceof" have. The instanceof keywword doesn't have a type.
When writing code like you cited, you are taking advantage of a DSL. Treat words like compile and optional as keywords in that DSL. Unless you are writing your own DSL (as opposed to taking advantage of existing one, which is what this question is about), don't think of types being associated with those things.
As for the question about ctrl+space, Eclipse won't do anything special with that in this context unless you are using a plugin which provides support for that. Even with plugin support there will still be limitations because you can define your own configurations. If you were going to define a configuration named "jeffrey" and you typed "jeff" followed by ctrl+space, there is no way for the IDE to know you want it to turn that into "jeffrey".
I hope that helps.

Are there any means in Scala to split a class code into many files?

There are 2 reasons for me to ask:
1. I'd like a better code fragmentation to facilitate version control on per-function level
2. I struggle from some attention deficit disorder and it is hard for me to work with long pieces of code such as big class files
To address these problems I used to use include directives in C++ and partial class definitions and manually-definable foldable regions in C#. Are there any such things available in Scala 2.8?
I've tried to use editor-fold tag in NetBeans IDE, but it does not work in Scala editor unfortunately :-(
UPDATE: As far as I understand, there are no such facilities in Scala. So I'd like to ask: someone who has any connection to Scala authors, or an account on their Bugzilla (or whatever they use), please, suggest them an idea - they should probably think of introducing something of such (I was fascinated by C# regions and partial classes for example, and plain old includes also look like a convenient tool to have) to make Scala even more beautiful through laconicity, IMHO.
How about doing it with traits? You define it like this:
trait Similarity
{
def isSimilar(x: Any): Boolean
def isNotSimilar(x: Any): Boolean = !isSimilar(x)
}
...and then you use it like so:
class Point(xc: Int, yc: Int) extends Similarity
{
var x: Int = xc
var y: Int = yc
def isSimilar(obj: Any) =
obj.isInstanceOf[Point] &&
obj.asInstanceOf[Point].x == x
}
If the class Point were bigger, you could split it further into traits, resulting in the division that you want. Please note, however, that I don't think this is advisable, as it will make it very difficult to get a good overview of your code, unless you already know it by heart. If you can break it in a nice way, however, you might be able to get some nice, reusable blocks out of it, so in the end it might still be worth doing.
Best of luck to you!
//file A.scala
trait A { self: B =>
....
}
//file B.scala
trait B { self: A =>
....
}
//file C.scala
class C extends A with B
I suggest to read white paper by Martin at this link. In this white paper 'Case Sudy: The Scala Compiler' chapter will give you idea about how you can achieve component based design having code in several separate files.
Scala code folding works properly in IDEA.
The version control tools I work with (bzr or git, mostly) have no trouble isolating changes line-by-line. What use case do you have--that's common enough to worry about--where line-level isolation (which allows changes to independent methods to be merged without user intervention) is not enough?
Also, if you can't focus on something as large as one class with many methods, use more classes. A method generally requires you to know what the other methods are, what the fields are, and so on. Having that split across separate files is just asking for trouble. Instead, encapsulate your problem in a different way so you can work with smaller self-contained chunks at a time.

Writing applications with Scala actors in practice

I've now written a few applications using scala actors and I'm interested in how people have approached or dealt with some of the problems I've encountered.
A plethora of Message classes or !?
I have an actor which reacts to a user operation and must cause something to happen. Let's say it reacts to a message UserRequestsX(id). A continuing problem I have is that, because I want to modularize my programs, a single actor on its own is unable to complete the action without involving other actors. For example, suppose I need to use the id parameter to retrieve a bunch of values and then these need to be deleted via some other actor. If I were writing a normal Java program, I might do something like:
public void reportTrades(Date date) {
Set<Trade> trades = persistence.lookup(date);
reportService.report(trades);
}
Which is simple enough. However, using actors this becomes a bit of a pain because I want to avoid using !?. One actor reacts to the ReportTrades(date) message but it must ask a PersistenceActor for the trades and then a ReportActor to report them. The only way I've found of doing this is to do:
react {
case ReportTrades(date) =>
persistenceActor ! GetTradesAndReport(date)
}
So that in my PersistenceActor I have a react block:
react {
case GetTradesAndReport(date) =>
val ts = trades.get(date) //from persietent store
reportActor ! ReportTrades(ts)
}
But now I have 2 problems:
I have to create extra message classes to represent the same request (i.e. "report trades"). In fact I have three in this scenario but I may have many more - it becomes a problem keeping track of these
What should I call the first and third message ReportTrades? It's confusing to call them both ReportTrades (or if I do, I must put them in separate packages). Essentially there is no such thing as overloading a class by val type.
Is there something I'm missing? Can I avoid this? Should I just give up and use !? Do people use some organizational structure to clarify what is going on?
To me, your ReportTrades message is mixing two different concepts. One is a Request, the order is a Response. They might be named GetTradesReport(Date) and SendTradesReport(List[Trade]), for example. Or, maybe, ReportTradesByDate(Date) and GenerateTradesReport(List[Trade]).
Are there some objections to using reply? Or passing trades around? If not, your code would probably look like
react {
case ReportTrades(date) => persistenceActor ! GetTrades(date)
case Trades(ts) => // do smth with trades
}
and
react {
case GetTrades(date) => reply(Trades(trades.get(date)))
}
respectively.