What does it mean to use Proper Windsor Service Overrides? - c#

I am trying to create an index agent service for a multi-instance Solr install using SolrNet. I have created the service, which will use an interface to create multiple agents to index with. These agents are specified in an external configuration file and instantiated dynamically. There can be 0-n of each agent type, for instance (note the url differences):
PersonAgent http://localhost:8080/solr
ProductAgent http://localhost:8080/solr
ProductAgent http://localhost:9999/solr
This of course needs to map to something like this:
ISolrOperations<Person>
ISolrOperations<Product>
ISolrOperations<Product>
Based on my needs and the fact that SolrNet does not support multiple instances for its default container, I am trying to use Castle Windsor for this. According to the SolrNet wiki at http://code.google.com/p/solrnet/wiki/MultiCoreAccess this is pretty straightforward.
var solrFacility = new SolrNetFacility("http://localhost:8983/solr/defaultCore");
solrFacility.AddCore("core0-id", typeof(Product), "http://localhost:8983/solr/product");
solrFacility.AddCore("core1-id", typeof(Product), "http://localhost:8983/solr/product2");
solrFacility.AddCore(typeof(Person), "http://localhost:8983/solr/person"); // no need to set an explicit ID since it's the only core for Person
container.AddFacility("solr", solrFacility);
ISolrOperations<Person> solrPerson = container.Resolve<ISolrOperations<Person>>();
ISolrOperations<Product> solrProduct1 = container.Resolve<ISolrOperations<Product>>("core0-id"); // use proper Windsor service overrides instead of resolving like this
ISolrOperations<Product> solrProduct2 = container.Resolve<ISolrOperations<Product>>("core1-id");
I'm not completely lost with the idea of IoC, but I am unsure what the wiki author meant with the comment to "use proper Windsor service overrides instead of resolving like this" as stated in the code sample. Obviously the example explicitly identifies the core via an id, but is there a better/more flexible way?

What I meant is that you normally don't resolve ISolrOperations<T> directly from the container.
Instead, you use service overrides or other Windsor mechanisms to define which ISolrOperations<T> component (which core) to pass to other components, especially when you have multiple cores with the same document type, e.g. in this example there are two components registered under the service type ISolrOperations<Product>.

Related

Resolve without Type information in unity

Unity supports resolve based on types
T obj = container.Resolve<T>("id");
that means without knowing T, I can not resolve, I am writing some extension methods for my unity container where I want to add Resolve method which would return object type.
object obj = container.Resolve("id");
because when registering I already know T so I can keep type in a dictionary with "ID". This is unreliable as unity can itself resolve some types(even when not registered) Is there a simpler and reliable way to do resolve using only the Id for resolving?
This is diffrent from calling generic method from reflection due to performance issues and also since the resource is already registered with unity for DI hence i want to use existing solution to keep it consistent.
Now if i can resolve something by ID and return object or dynamic i can use type converters internally to convert it to expected type later. Upfront i do not know type which has to be used.
If object is your interface, you can use that, of course:
container.RegisterType<object, ObscureService>( "service" );
container.RegisterType<object, SecretPlugin>( "plugin" );
object unknown = container.Resolve<object>( "service" );
object anotherUnknown = container.Resolve<object>( "plugin" );
This has very limited (sensible) use, though. I'd say you should only use this if you act on direct request from the user and the resolved unknown is some kind of view model that's only used to be presented back to the user.
If code requests the object, there's no reason why that code should not somehow be able to know what it's requesting.

Roslyn CodeFix with multiple variants to fix

I have a CodeFix provider, purpose of which to inject service to current class, like add new private field, parameter to constructor, assignment statement in constructor, using ServiceNamespace, and use of this field in proper place(s).
At some point, I have a name of this service, and I need to find namespace for this service to add correct using. I'm doing this via compilation.GetSymbolsWithName(typeName), but this method can return several matched symbols from different namespaces/assemblies.
So, the question: is there any way I can show this variants to user so he can decide the correct type?
For each diagnostic, you can add more than one fix.

How Can I Redesign My C# Application To Avoid Constructor Injection Overload?

I am still new to DI and Unit Tests. I have been tasked with adding Unit Tests to some of our legacy code. I am working on a WCF web service. A lot of refactoring has had to be done. Monster classes split into separate classes that make sense. Monster methods split to multiple methods. And lastly, creating interface classes for external dependencies. This was done initially to facilitate mocking those dependencies for unit tests.
As I have gone about this the list of dependencies keeps growing and growing. I have other web services to call, SQL Servers and DB2 Databases to interact with, a config file to read, a log to write to, and reading from Sharepoint data. So far I have 10 dependencies. And every time I add one it breaks all my Unit Tests since there is a new parameter in the constructor.
If it helps, I am using .Net 4.5, Castle Windsor as my IOC, MSTest, and Moq for testing.
I have looked here How to avoid Dependency Injection constructor madness? but this doesn't provide any real solution. Only to say "your class may be doing too much." I looked into Facade and Aggregate services but that seemed to just move where things were.
So I need some help on how to make this class to "less" but still provide the same output.
public AccountServices(ISomeWebServiceProvider someWebServiceProvider,
ISomeOtherWebProvider someOtherWebProvider,
IConfigurationSettings configurationSettings,
IDB2Connect dB2Connect,
IDB2SomeOtherData dB2SomeOtherData,
IDB2DatabaseData dB2DatabaseData,
ISharepointServiceProvider sharepointServiceProvider,
ILoggingProvider loggingProvider,
IAnotherProvider AnotherProvider,
ISQLConnect SQLConnect)
{
_configurationSettings = configurationSettings;
_someWebServiceProvider = someWebServiceProvider;
_someOtherWebProvider = someOtherWebProvider;
_dB2Connect = dB2Connect;
_dB2SomeOtherData = dB2SomeOtherData;
_dB2DatabaseData = dB2DatabaseData;
_sharepointServiceProvider = sharepointServiceProvider;
_loggingProvider = loggingProvider;
_AnotherProvider = AnotherProvider;
_SQLConnect = SQLConnect;
}
Almost all of the there are in other components but I need to be able to use them in the main application and mock them in unit tests.
Here is how one of the methods is laid out.
public ExpectedResponse GetAccountData(string AccountNumber)
{
// Get Needed Config Settings
...
// Do some data validation before processing data
...
// Try to retrieve data for DB2
...
// Try to retrieve data for Sharepoint
...
// Map data to response.
...
// If error, handle it and write error to log
}
Other methods are very similar but they may be reaching out to SQL Server or one or more web services.
Ideally what I would like to have is an example of an application that needs a lot of dependencies, that has unit tests, and avoids having to keep adding a new dependency to the constructor causing you to update all your unit tests just to add the new parameter.
Thanks
Not sure if this helps, but I came up with a pattern I called GetTester that wraps the constructor and makes handling the parameters a little easier. Here's an example:
private SmartCache GetTester(out Mock<IMemoryCache> memory, out Mock<IRedisCache> redis)
{
memory = new Mock<IMemoryCache>();
redis = new Mock<IRedisCache>();
return new SmartCache(memory.Object, redis.Object);
}
Callers look like this if they need all the mocks:
SmartCache cache = GetTester(out Mock<IMemoryCache> memory, out Mock<IRedisCache> redis);
Or like this if they don't:
SmartCache cache = GetTester(out _, out _);
These still break if you have constructor changes, but you can create overloads to minimize the changes to tests. It's a hassle but easier than it would otherwise be.
So possibly your classes might be doing too much. If you're finding that you're constantly increasing the work that a class is doing and as a result are needing to provide additional objects to assist in those additional tasks then this is probably the issue and you need to consider breaking up the work.
However, if this isn't the case then another option is to have the classes take in a reference to a dependency class that provides access to either the instantiated concrete objects that implement your various interfaces or instantiated factory objects which can be used to construct objects. Then instead of constantly passing new parameters you can just pass the single object and from there pull or create objects as necessary from that.

Autofac resolve dependant services by name

Is it possible to register a single service that has dependencies that can change depending on a setting?
For instance
A DBExecutor requries a different DBconnection object depending which geographical region it is running under.
I've tried something like
builder.RegisterType<DbConnection>().Named<IDbConnection>("US")
builder.RegisterType<DbConnection>().Named<IDbConnection>("AU")
builder.RegisterType<SqlExecutor>().As<IDbExecutor>();
and I'd like to resolve the service with something like
var au = container.ResolveNamed<IDbExecutor>("AU");
var us = container.ResolveNamed<IDbExecutor>("US");
However this doesn't work because the IDbExecutor itself hasn't been registered with a key, and if I try a normal Resolve it wont work as it cannot create the dependent services.
Basically I just want an instance of of IDbExecutor with a DBConnection based upon a certain parameter.
I'm trying to do this in a more general sense so I'm trying to avoid any specific code where I can.
The current generic code I have that doesn't use keyed services looks like
var job = (IJob) lifetimeScope.Resolve(bundle.JobDetail.JobType);
where JobType is a class Type and depending on if this is possible the final version would look something like
var job = (IJob) lifetimeScope.Resolve(bundle.JobDetail.JobType, bundle.JobDetail.JobDataMap["Region"]);
where bundle.JobDetail.JobDataMap["Region"] would return either "AU" or "US"
You won't be able to rig it to resolve a named IDbExecutor because you didn't register it as named. It's also probably not the best idea since it implies that IDbExecutor somehow "knows" about its dependencies, which it shouldn't - the implementation knows, but the interface/service doesn't - and shouldn't.
You can get something close to what you want by updating the SqlExecutor to use the IIndex<X,B> relationship in Autofac. Instead of taking just an IDbConnection in your constructor, take an IIndex<string,IDbConnection>.
When you need to get the connection, look it up from the indexed dictionary using the job type:
public class SqlExecutor
{
private IIndex<string, IDbConnection> _connections;
public SqlExecutor(IIndex<string, IDbConnection> connections)
{
this._connections = connections;
}
public void DoWork(string jobType)
{
var connection = this._connections[jobType];
// do something with the connection
}
}
Another way to do it would be to create a delegate factory for the SqlExecutor that takes in the job type and automatically picks the right named service. That's a bit more involved so check out the documentation for an example.

Structure Map 2.6.1

In my current project I'm currently trying to replace the Windsor IoC in favour of structure map (2.6.1). But having a bit of problem registering some generic types. How would I register IFilterConverter<T> to use FilterConverter<SomeSpecificType>. I've tried ConnectImplementationsToTypesClosing(IFilterConverter) but from what I've read (Jimmy Bogard's article) I would need a concrete type defined like so:- SomeConcreteType : IFilterConverter<SomeSpecificType> for that to work and I don't have that.
So to reiterate if I have a type that takes a constructor argument IFilterConverter<SomeSpecificType>, I want structure map to provide me with FilterConverter<SomeSpecificType>.
With Windsor I was using the XML config option (which I want to get away from) But all I did was just set up the configuration like so:
<component id="IFilterConverter" service="SomeNamespace.IFilterConverter`1, SomeNamespace" type="SomeNamespace.FilterConverter`1, SomeNamespace" lifestyle="PerWebRequest">
How do I do the equivalent in SM (using code, not XML config files)
Thanks
I think this should do it.
_container = new Container();
_container.Configure(x =>
{
x.For(typeof (IFilterConverter<>)).Use(typeof (FilterConverter<>));
});

Categories