collections,castle-windsor,decorator , Decorate each item resolved in a collection with Castle Windsor


Decorate each item resolved in a collection with Castle Windsor

Question:

Tag: collections,castle-windsor,decorator

Suppose I have an interface with multiple base implementations:

interface IPrinter
{
    void Print();
}

class Printer1 : IPrinter
{
    public void Print()
    {
        Console.WriteLine(GetType());
    }
}

class Printer2 : IPrinter
{
    public void Print()
    {
        Console.WriteLine(GetType());
    }
}

I also have a decorator implementation:

class ModifyingPrinter : IPrinter
{
    private readonly IPrinter _printer;

    public ModifyingPrinter(IPrinter printer)
    {
        _printer = printer;
    }

    public void Print()
    {
        Console.Write("Modified ");
        _printer.Print();
    }
}

Finally, I have a service which requires a collection of the interface:

class Service
{
    private readonly IEnumerable<IPrinter> _printers;
    public Service(IEnumerable<IPrinter> printers)
    {
        _printer = printer;
    }

    public void Print()
    {
        foreach (var printer in _printer)
        {
            printer.Print();
        }
    }
}

What I'd like is for Service to have Printer1 and Printer2 in the collection, each decorated with ModifyingPrinter so that the output of Service.Print() is:

Modified Printer1
Modified Printer2

I've tried registering the classes as follows:

var container = new WindsorContainer();

container.Kernel.Resolver.AddSubResolver(
    new CollectionResolver(container.Kernel, true));

container.Register(Component.For<IPrinter>()
                            .ImplementedBy<ModifyingPrinter>()
                            .LifestyleTransient());
container.Register(Component.For<IPrinter>()
                            .ImplementedBy<Printer1>());
container.Register(Component.For<IPrinter>()
                            .ImplementedBy<Printer2>());

container.Register(Component.For<Service>());

But this results in the following output:

Modified Printer1
Printer1
Printer2

It appears that Windsor's CollectionResolver is supplying one each of all implementations of IPrinter (which is understandable) instead of recognizing that ModifyingPrinter is a decorator and using it to wrap the other two implementations.

My question: Is there a way to register these classes so that the collection contains only decorated base implementations?

I read in another post somewhere that I can create an interceptor and register Printer1 and Printer2 with the interceptor, but I'd like to keep to the decorator pattern if I can.


Answer:

As it turns out, Castle.Windsor cannot do what I'm looking for out of the box. I tried looking into creating a new resolver to handle this scenario, but didn't get very far.

In the end, I restructured to use a true factory to decorate the classes.

class PrinterModifierFactory : IPrinterModifierFactory
{
    private Func<IPrinter, IPrinter> _decorate;
    private IEnumerable<IPrinter> _printers;

    public PrinterModifierFactory(Func<IPrinter, IPrinter> decorate,
                                  IEnumerable<IPrinter> printers)
    {
        _decorate = decorate;
        _printers = printers;
    }

    public IEnumerable<IPrinter> GetAll()
    {
        return _printers.Select(_decorate);
    }
}

Then I modified my service to simply receive and instance of this factory (via the interface, of course) instead of the IEnumerable<IPrinter>.

class Service
{
    private readonly IEnumerable<IPrinter> _printers;
    private IPrinterModifierFactory factory;

    public Service(IPrinterModifierFactory factory)
    {
        _factory = factory;
    }

    public void Print()
    {
        _Initialize();

        foreach (var printer in _printers)
        {
            printer.Print();
        }
    }

    void _Initialize()
    {
        if (_printers != null) return;

        _printers = factory.GetAll().ToList();
    }
}

(I've omitted details like null checks for brevity.)

Finally, in the installer, I could register the factory and the decorating method.

container.Register(Component.For<IPrinterModifierFactory>()
                            .ImplementedBy<PrinterModifierFactory>());
Func<IPrinter, IPrinter> decorator = p => new ModifyingPrinter(p);
container.Register(Component.For<Func<IPrinter, IPrinter>>()
                            .Instance(decorator));

The answer was to be a bit more explicit in my architecture.


Related:


Loop by Object inside another Object in Java


java,list,oop,collections
I'm not sure how to ask this in word so here's an example : Building class have a data like this : Map<Season, List<Info>> infosBySeason = new TreeMap<Season, List<Info>>(); What I'd like to do is loop for each Building, print by Season infos. Like : Season 1 : Building 1...

Iterating through a list searching for duplicates


java,list,collections,iterator
So I have this task that I must do a dice roller and then search for a certain combination if it was rolled. I have an overriden equals method, that checks for the combination and it is working properly. Every object from the class Dice has its own string array...

PLSQL move data from csv list stored in varchar2 to a collection of integers


sql,oracle,collections,plsql
Oracle Express 11G R2: In PLSQL I have a varchar2 containing a CSV list of values like this: vList:='1212,3232,3232,4343,54545,65654,65665,65654,788787' I would like to move these into a collection, so i create a new type: CREATE TYPE INTEGER_TT AS TABLE OF INTEGER; then declare my variable: my_list INTEGER_TT; What is the...

“Segmentize” collection with lodash


javascript,collections,lodash
I have a collection col1 var col1 = [1, 8, 9, 10, 2, 54, 7]; I have another collection col2 var col2 = [1, 8, 23, 9, 46, 10, 2, 54, 78, 7] ...that I know it contains every element of col1, plus some other elements I want to...

Get those elements from a List of custom class objects whose one property value is parseable to double


c#,.net,linq,list,collections
I have a list of custom class objects in C# with class structure like this: public class ABC { int ID; string Text1; string Text2; } This list stores data like this: +-----+-------+--------+ | ID | Text1 | Text2 | +----------------------+ | 1 | PQR | test1 | | |...

Performance of element-compare in java collections


java,performance,collections
Problem: Given two Collection<?>s, check if both contain the same elements. Assuming that the actual implementation of the collection is unknown Assuming that the elements do not occur in the same order Assuming that no element does occur twice in the same collection Solution 1: boolean equals = c1.containsAll(c2) &&...

Couchbase Bulk loading error with upsert() (.NET SDK 2.0)


c#,.net,collections,couchbase,upsert
I have encountering an error when inserting bulk data with the upsert function and cannot figure out how to fix it. Anyone know what is wrong here? What the program is essentially doing is grabbing data from a SQL server database and loading into our Couchbase bucket on an Amazon...

Iterator for an array list of Class


java,collections,iterator,listiterator
Am New to Java so please bear with me if my question seems to be silly. I am learning collections,I have written a program which will store student names id and marks.I am storing all these in a Arraylist. Using for loop I am able to print the values in...

Keep (minim) object in a collection by two attribute keys in java


java,collections,set,comparator,treeset
For example I have a list that contains 3 objects: List<Student> studentList= new ArrayList<Student>(); list.add(new Student("name1", 5); list.add(new Student("name3", 6); list.add(new Student("name1", 7); class Student{ String name; Integer grade;} My filtering logic: if name is equal then i need to filter out the objects that have maximum grade - so...

How to convert single element list to java 8 optional


java,collections,java-8,optional
How to nicely convert list containing one or zero elements to Optional? The ugly code: List<Integer> integers = new ArrayList<>(); Optional<Integer> optional = integers.size() == 0 ? Optional.empty() : Optional.of(integers.get(0)); ...

Resolving Interface with generic type constraint with Castle Windsor


c#,generics,castle-windsor
Given the interface where FooRequest and FooResponse are abstract: public interface IFooHandler<TRequest, TResponse> where TRequest : FooRequest where TResponse : FooResponse { TResponse CheckFoo(TRequest request); } An implementation of: public class MyFooHandler : IFooHandler<MyFooRequest, MyFooResponse> { public MyFooResponse CheckFoo(MyFooRequest request) { /* check for foos */ } } How would...

Merge multiple lists based on List priority


java,sorting,collections,priority
I have couple of lists where each list has different priority. When i merge these lists i should get with height priority on top. Assume i have 3 lists and different objects value common in 3 lists should come first and then the top priority list should be appended vice...

I can't use in GWT Collections.unmodifiableList(List l) to make only readable my List, because isn't serializable, alternative ways?


java,list,collections,gwt-rpc,unmodifiable
I'm using GWT-RPC to create an application. At certain point the server return a Collection using Collections.unmodifiableList(List l) to the client. The client give an error: [WARN] Exception while dispatching incoming RPC call com.google.gwt.user.client.rpc.SerializationException: Type 'java.util.Collections$UnmodifiableList' was not included in the set of types which can be serialized by this...

Where can I find the definitions of System.Collections.Concurrent classes in the mono source code?


c#,collections,mono
I am looking for the source code of the System.Collections.Concurrent classes, especially ConcurrentQueue and ConcurrentDictionary in the mono sources. I am unable to find them. I was looking in the corlib Directory: https://github.com/mono/mono/tree/master/mcs/class/corlib but it does not contain the System.Collections.Concurrent package. Even using the repository search feature of github did...

Java Generic Map with Generic Type as key/ values


java,generics,collections
I want to write a method which takes a Map as an parameter, which can contain any object as its value. I am trying to implement it using generics, but I am unable to implement it. Below is the code that I have tried so far. This code as two...

VBA values of collection into Excel using VBA


excel,vba,excel-vba,dictionary,collections
I am trying to copy values into an Excel sheet using VBA code. I have been trying to use a dictionary (as using in my function (8) and utilized in section (3) and (4) ). When I had it set as a dictionary, everything was off by one so I...

Returning an Iterator from String[] [duplicate]


java,arrays,collections
This question already has an answer here: Iterator of Object[] 2 answers I have a class foo with a field String[] bar. I want foo to implement Iterable<String>. So I'm writing @Override public Iterator<String> iterator() { // ToDo - return some function of `bar` } What can I put...

Should remove(Object) be remove(? super E)


java,generics,collections,super,contravariance
In this answer, I tried to explain why the Collection method add has the signature add(E) while remove is remove(Object). I came up with the idea that the correct signature should be public boolean remove(? super E element) And since this is invalid syntax in Java, they had to stick...

Converting collection to array with no extra memory


java,arrays,performance,memory,collections
I need to convert Map into 2D array, so I've wrote this piece of code but it eats a lot of memory and I can't figure out why. private DataItem[][] convertDataToArrays(boolean[] filter, Map<Integer, List<T>> dataSet) double[] data = new double[sizeOfNewVector]; DataItem[][] reducedData = new DataItem[dataSet.size()][]; for (int i = dataSet.size()...

Which Namespace holds Component.For in Castle Windsor?


c#,castle-windsor
I'm learning Castle Windsor and I found this tutorial. In it, there's this code: private void button1_Click(object sender, EventArgs e) { // CREATE A WINDSOR CONTAINER OBJECT AND REGISTER THE INTERFACES, AND THEIR CONCRETE IMPLEMENTATIONS. var container = new WindsorContainer(); container.Register(Component.For<Main>()); container.Register(Component.For<IDependency1>().ImplementedBy<Dependency1>()); container.Register(Component.For<IDependency2>().ImplementedBy<Dependency2>()); // CREATE THE MAIN OBJECT AND INVOKE...

Delete single model from collection in Backbone.View


javascript,backbone.js,collections,model
var PlayersView = Backbone.View.extend({ collection: players, //collection of players el: "#playersList", //I bind to the class render: function () { this.$el.html(""); for (var i=0; i<this.collection.size(); i++) { var player = this.collection.at(i); this.$el.append("<li "+"value='"+player.get("id")+"'>"+player.get("names")[0]+" "+player.get("surnames")[0]+" <a href='#' class='edit'>[edit]</a>"+"</li>"); } //what I render is in the picture below return this; }, events:...

how to keep 10 biggest integer while reading a list in java?


java,sorting,collections
I have a list of integer in a list and want to keep the 10 biggest while I'm iterating over the list and keep them in a TreeSet. I'm using this code : for(Integer i : list) { if (treeSet.size() < 10) { treeSet.add(i); } else if (i > treeSet.last())...

Collection without duplicates (based on id) but keeps the highest version number


java,collections,duplicates
This seems like something that should have a standard solution, but I can't find what I'm looking for. It's not difficult to implement by hand, but perhaps I'm just missing a tool in my toolbox? In pseudo-code, I want a set-like collection that, given existing entries {id_1, v_1}, {id_2, v_2}...

Castle Windsor & Command Pattern


c#,dependency-injection,inversion-of-control,castle-windsor
I am trying to implement a Command, CommandHandler and CommandDispatcher pattern using Castle Windsor without manually asking the container to resolve a CommandHandler based on Command type (which is generally considered an anti-pattern). I found this old article, but the implementation of ITypedFactoryComponentSelector has changed, so now it returns a...

Why doesn't my sample throw ConcurrentModificationException [duplicate]


java,collections,concurrentmodification
This question already has an answer here: Why isn't this code causing a ConcurrentModificationException? 4 answers I wrote this example following a test ConcurrentModificationException concept: public class Person { String name; public Person(String name) { this.name = name; } } public static void main(String[] args) { List<Person> l =...

complex collection in java


java,collections
I need to define a collection of user defined objects with the following access methods: access by the object's primary key (unique) access by index of the collection sorted on a secondary key (not unique) Each object has a primary key and a secondary key (not guaranteed unique). When an...

getting a value from a map in java with index


java,collections
The item shown below is the result obtained from debugging a map {0={PRODUCT_TYPE.PRODUCT_AMT=200}} To store this value in a string I have used this code String amountCheck=(String) productsFieldMap.get("PRODUCT_TYPE.PRODUCT_AMT"); However this does not seems to work. Can anyone suggest me a way to do this? The productsFieldMap represents the map where...

why java API prevents us to call add and remove together?


java,list,collections,listiterator
As per Java API- IllegalStateException - if neither next nor previous have been called, or remove or add have been called after the last call to next or previous remove()- Removes from the list the last element that was returned by next() or previous() (optional operation). This call can only...

LoDash - DeepFlatten array of objects


javascript,collections,lodash,flatten
I have the following collection. Each object may have a children array of objects, which may have a children array of objects and so on... [ { "name": "John", "age": 24, "children": [ { "name": "Jack", "age": 53, "children": [ { "name": "Jenny", "age": 88 } ] } ] },...

joining two collections in C# or JavaScript


javascript,c#,linq,collections
I have two objects of "pseudotype" Hash(int key, list values) that I need to combine into one based on the key. For example, [{1, {a, b, c}}, {2, {apple, pear}}, {3, {blue, red}}] and [{2, {tomato}}, {3, {pink, red}}, {4, {x, y, z}}] The result that I need is: [{1,...

Is there a Java class that lets me iterate trough the last x elements? [duplicate]


java,list,collections,iterator
This question already has an answer here: How to start iterating through ArrayList from set index? [closed] 5 answers I am looking for something like a LinkedList with a function that returns an iterator for the last x elements. For example: LinkedList<Oky> obj; obj.add(a); obj.add(b); obj.add(c, d, e, f,...

add subitems to meteor document


mongodb,meteor,collections,insert-update
I have a meteor collection "list" that has the following data structure. "list" : [ { "_id" : "id", "author" : "authorId", "createdOn" : "DateTime", "description" : "description", "items" : [ { "item1" : { "itemComplete" : "Boolean", "itemName" : "item name", "itemDescription" : "item description", } }, { "item2"...

Java - Create sublist from a list based on suffix


java,arraylist,collections,iterator,sublist
I'm trying to create sublists from a list based on the suffix. public class Test { public static void main(String args[]) { List<List<String>> subList = new ArrayList<List<String>>(); List<String> myList = new ArrayList<String>(); myList.add("Text_1"); myList.add("XYZ_3"); myList.add("ABC_1"); myList.add("Text_2"); myList.add("Text_3"); myList.add("XYZ_1"); myList.add("XYZ_2"); myList.add("ABC_2"); for (String item : myList) { List<String> tempList = new...

Finding the desired amount of smallest Doubles in an ArrayList


java,arraylist,collections
I have an ArrayList filled with Double values, and based on user input (an int), I need to find the indices of the entered amount of smallest Doubles from this List. For example, if the user were to type in 5, and the ArrayList looked as such (is actually much...

“Class.Property” is not accessible in this context because it is 'Private'


vb.net,loops,collections
I'm looking access private member of a class in myproject.vb file. My function header in myproject.vb looks like this, Public Function MyVbFunction(ByVal objRequest As BookRequest) As Integer Try For Each book As Book In objRequest.m_Books If Myvbfucntion2(book) = 1 Then Return True End If Next End Try End Function Book...

Merge two or more T in List based on condition


c#,linq,collections
I have the below class: public class FactoryOrder { public string Text { get; set; } public int OrderNo { get; set; } } and collection holding the list of FactoryOrders List<FactoryOrder>() here is the sample data FactoryOrder("Apple",20) FactoryOrder("Orange",21) FactoryOrder("WaterMelon",42) FactoryOrder("JackFruit",51) FactoryOrder("Grapes",71) FactoryOrder("mango",72) FactoryOrder("Cherry",73) My requirement is to merge the...

Backbone.js collection fetch not setting response objects as models


backbone.js,collections,fetch
When fetching a collection, my api response has 10 objects, but the resulting Backbone collection only has 1 model with an attributes array containing the 10 response objects....to put it another way, the fetch is not creating models out of the objects in my response...and I don't know why. Model...

Async GetMany method in Repository


c#,asynchronous,collections
I have repository method which returns collection according to filter public IEnumerable<T> GetMany(Expression<Func<T, bool>> filter = null) { IQueryable<T> query = DbSet; if (filter != null) { query = query.Where(filter); } return query.ToList(); } Now i want to write this method as Async. And this is my problem. Should i...

Why does the Java.Util.Stack not pop last element in the loop?


java,collections,stack
I have a very Basic Question Stack<Integer> s=new Stack<integer>(); s.push(New Integer(1)); s.push(New Integer(2)); s.push(New Integer(3)); for(int i=0;i<s.size();i++){ System.out.println("i: "+i+" size:"+s.size()); System.out.print(s.pop()); if(s.size()>=1) System.out.print(" ->"); } This results in an output of 3->2-> And Not 3->2->1 Shouldn't the loop run thrice , Is the condition i < s.size() changing as the...

Update multiple values in an oracle table using values from an APEX collection


sql,oracle,collections,apex
I am using APEX collections to store some values and pass them between pages in Oracle Application Express 4.2.3. I would like to then perform an update statement on a table called "project" with the values from the collection. My code so far is as follows: update project SET name=c.c002,...

What is the best way to iterate two hashmap in same loop in java?


java,data-structures,collections
What's the best way to iterate over the below two maps together? I want to compare two maps values which are strings and have to get the keys and values. HashMap<String, String> map1; HashMap<String, String> map2; ...

Using counter on array for one value while keeping index of other values


python,collections
After reading the answers on this question How to count the frequency of the elements in a list? I was wondering how to count the frequency of something, and at the same time retreive some extra information, through something like an index. For example a = ['fruit','Item#001'] b = ['fruit','Item#002']...

Meteor, '/users/insert' is already defined


javascript,facebook,mongodb,meteor,collections
I'm creating basic Administration Panel and I didn't work with MongoDB yet. For development purposes I left autopublish and insecure in the project. In order to render users from database (Accounts-ui + Accounts-facebook) i need a handler for Users = new Mongo.Collection("users"); but during compilation there is following error: '/users/insert'...

Search for key in Map when the values are in ArrayList [closed]


java,arraylist,collections,hashmap,key-value
I am new to the collections in Java , I have a HashMap<String, List<String>>. I want to search for a key from the Map when a value is given. The map stores the data of a state as key and its cities as the list. So it is assumed that...

Entity Framework, Code First, Update independent association (Collection)


c#,entity-framework,collections,ef-code-first
to explain the problem I have a simple model with a class Person: public class Person { public int Id { get; set; } public virtual string Name { get; set; } } and a class School with a collection of Persons: public class School { public int Id {...

ArrayList cannot be converted to string.


java,arraylist,collections
Okay, I'm making a CD collection Program and everything was going well as I followed along my lesson but then I ran into the problem of wanting to make it show up in the jTextArea. I bet there is a simple solution but I cannot find one. I'm new to...

Mapping a list to Map Java 8 stream and groupingBy


java,collections,lambda,java-8
I have this simple Bean class: public class Book { public Book(Map<String, String> attribute) { super(); this.attribute = attribute; } //key is isbn, val is author private Map<String, String> attribute; public Map<String, String> getAttribute() { return attribute; } public void setAttribute(Map<String, String> attribute) { this.attribute = attribute; } } In...

VBA Debugger shows only 256 elements of a collection


excel-vba,debugging,collections
the title explains my problem. Im working on an excelmakro and my questions is, is there an option that the debugger shows all elements like it does with an array? And if not, is the only workaround the storage of my classobjects in an array after inflating the collection? I...

Java generic usage error


java,collections,java-generics
The code below uses simple generics and compiles correctly. When I try to create a object of type McDelayQueue, I get an error. public class McDelayQueue<E extends Delayed & IValue<K>, K> extends DelayQueue<E> { final Set keys = Collections.newSetFromMap(new ConcurrentHashMap<K, Boolean>()); @Override public E take() throws InterruptedException { E data...

Reflection , java , iterate on collection


java,reflection,collections
I'm writing a function that will iterate on some collection , I don't know what collection I'm getting , so I wrote this till now , the PrintFieldsOfClass will get some object or collection of objects and I will have to print the fields of the class , I have...