How can WCF Autofac Container (IContainer) can use in non WCF project classes?
Adding Autofac to Service project (on sample below) is the only solution or is there any other elegant way to achieve this.
Passing services as parameter in not feasible
Any help would be appreciated.
Wcf Service Project (Uses Autofac WCF)
public class DiscountWCFService
{
public IDiscountService service {get; set;}
}
Service Project
public class DiscountService : IDiscountService
{
public IDiscountRepository repository {get; set;}
}
public static class DiscountExtension
{
public static IDiscountProcessor GetProcessor(this Discount discount)
{
if(discount.Type=1) return TypeAProcessor();
if(discount.Type=2) return TypeBProcessor();
return null;
}
}
public class TypeAProcessor : IDiscountProcessor
{
// Is it possible to use Autofac?
// E.G. IService fooService = AutofacContainer.Resolve<IFooService>
}
public class TypeBProcessor : IDiscountProcessor
{
}
Entity Project
public class Discount
{
}
Using keyed registration in Autofac saved my day.
Sample solution for my case is
builder.RegisterType<TypeAProcessor>().As<IDiscountProcessor>().Keyed<IDataService>(Type.One);
builder.RegisterType<TypeBProcessor>().As<IDiscountProcessor>().Keyed<IDataService>(Type.Two);
builder.Register<Func<Discount, IDiscountProcessor>>(c =>
{
var componentContext = c.Resolve<IComponentContext>();
return (discount) =>
{
var processor = componentContext.ResolveKeyed<IDiscountProcessor>(discount.Type);
return dataService;
};
});