autofac baseclass property is null - autofac

Here is my setup with Asp.Net Mvc 3:
public abstract class BaseProvider
{
protected ICache Cache;
}
public interface ICache
{
void Add(string key, object data);
void Remove(string key);
...
}
public class MyCache : ICache
{
private static MemoryCache cache = MemoryCache.Default;
void Add(string key, object data)
{
...
}
}
public interface IEmployeeProvider
{
IEnumerable<Employee> GetEmployees(string department);
}
public class EmployeeProvider:BaseProvider,IEmployeeProvider
{
public IEnumerable<Employee> GetEmployees(string department)
{
**if (Cache.Get("employees_"+department)!=null)**
}
}
Starred line throws an error saying that Cache is null.
I tried to register the base class as a type but, I guess it is wrong.
My Autofac setup is like this:
builder.Register(r => new EmployeeProvider()).As<IEmployeeProvider>().InstancePerHttpRequest();
builder.Register(r => new MyCache()).As<ICache>().InstancePerHttpRequest();
builder.RegisterType<BaseProvider>().PropertiesAutowired();
What am I missing?

You should either register EmployeeProvider with PropertiesAutowired() or scan the assembly for every class that inherits from BaseProvider.
The first registration forgets the PropertiesAutowired(), the third line forgets the EmployeeProvider.

Related

Passing connection string to Entity framework at runt time for each call

My Entity framework context is as following
public partial class MyContext : DbContext, IMyContext
{
static MyContext()
{
System.Data.Entity.Database.SetInitializer<MyContext>(null);
}
public MyContext()
: base("Name=MyContext")
{
}
I am resolving it through autofac in the following way
builder.RegisterType(typeof(MainContext)).As(typeof(DbContext)).InstancePerLifetimeScope();
builder.RegisterType<MainContext>().As<IMainContext>().InstancePerRequest();
This db context gets called in repository layer
#region Fields
private readonly IMyContext _context;
#endregion
#region Constructors and Destructors
public EmployeeRepository(IMyContext context)
{
_context = context;
}
#endregion
public void Create(Employee emp)
{
this._context.Employee.Add(emp);
}
Now my issue is , I want to set the connection string dynamically per call. The connection string will be passed through a webapi which i want to pass on to this context. Can anyone help me how can i do that? I am confused about autofac here. Secondly how can i make sure each call sets connection string and does not cache it.
You can use a factory that will build the context and set the connectionstring for you.
public interface IContextFactory
{
IContext GetInstance();
}
public class MyContextFactory : IContextFactory
{
public IContext GetInstance()
{
String connectionString = this.GetConnectionString(HttpContext.Current);
return new MyContext(connectionString);
}
private String GetConnectionString(HttpContext context)
{
// do what you want
}
}
builder.RegisterType<MyContextFactory>()
.As<IContextFactory>()
.InstancePerRequest();
builder.Register(c => c.Resolve<IContextFactory>().GetInstance())
.As<IContext>()
.InstancePerRequest();
If you can't get connectionstring based on HttpContext, you can change contextFactory implementation to expect initialization by WebAPI before creating the instance. For example :
public interface IContextFactory
{
IContext GetInstance();
void Initialize(String connectionString);
}
public class MyContextFactory : IContextFactory
{
private String _connectionString;
public void Initialize(String connectionString)
{
this._connectionString = connectionString;
}
public IContext GetInstance()
{
if (this._connectionString == null)
{
throw new Exception("connectionString not initialized");
}
return new MyContext(this._connectionString);
}
}
At the beginning of your web API call (through attribute for example), you can call the Initialize method. Because the factory is InstancePerRequest you will have one instance for the duration of the request.
By the way, I'm not sure to understand this registration
builder.RegisterType(typeof(MainContext)).As(typeof(DbContext)).InstancePerLifetimeScope();
builder.RegisterType<MainContext>().As<IMainContext>().InstancePerRequest();
It looks buggy because you will have 2 different registration of the same type and not for the same scope, is it intended ? Furthermore, it doesn't sound a good idea to register a DbContext, do you need this registration ?
The following registration looks better :
builder.RegisterType<MainContext>()
.As<IMainContext>()
.As<DbContext>()
.InstancePerRequest();

Working with WorkerStateEvent without casting?

I am currently dispatching my Business Logic via the Concurrency API JavaFX offers. But there is one part I stumble over which does not feel clean to me.
Basically if you create a Service which may look like this
public class FooCommand extends Service<Foo> {
#Override protected Task<Foo> createTask() {
return new Foo();
}
}
and I set the onSucceeded
FooCommand fooCommand = CommandProvider.get(FooCommand.class);
fooCommand.setOnSucceeded(new FooSucceededHandler());
fooCommand.start();
to an instance of this class
public class FooSucceededHandler implements EventHandler<WorkerStateEvent> {
#Override public void handle(WorkerStateEvent event) {
Foo f = (Foo) event.getSource().getValue();
}
}
But as you can see I need to cast the value of the Worker to (Foo). Is there some cleaner way to do it?
You could just make your own abstract class:
public abstract class EventCallback<T> implements EventHandler<WorkerStateEvent> {
#Override
public void handle(final WorkerStateEvent workerStateEvent) {
T returnType = (T) workerStateEvent.getSource().valueProperty().get();
this.handle(returnType);
}
public abstract void handle(T objectReturned);
}
And then using it:
final EventCallback<MonType> eventCallback = new EventCallback<MonType>() {
#Override
public void handle(final MonType objectReturned) {
// DO STUFF
}
};
As it is also an EventHandler, it is compatible with JavaFX concurrent API.

creating NHibernate repositories in view models with IoC

I would like to how to correct build and handle with NHibernate repository and session in view models classes.
For example I use Caliburn Micro framework with Castle Windsor boostraper.
First I created NHibernate repository:
public interface IRepository{//I omitted not needed code for simplification}
public class NHibRepository: IRepository
{
private ISession _session;
public NHibRepository(ISession session)
{
_session=session;
}
// I omitted not needed code for simplification
}
Second I definied some POCO class and mapping class with Fluent NHibernate.
public class User{}
public class Profile{}
public class Album{}
public class UserMap : ClassMap<User>{}
public class ProfileMap : ClassMap<Profile>{}
public class AlbumMap : ClassMap<Album>{}
Now I need use NHibernate repositories in my view models.
public interface IViewModelA{}
public class ViewModelA : ScreenViewModel, IViewModelA
{
public NHibRepository<User> UserRepo{get;set;}
public NHibRepository<Profile> ProfileRepo{get;set;}
}
public interface IViewModelB{}
public class ViewModelB : Screen, IViewModelB
{
public NHibRepository<Profile> ProfileRepo{get;set;}
public NHibRepoistory<Album> AlbumRepo{get;set;}
}
When I am creating repository class for some entity class I need pass session to NHibRepository construtor.
UserRepo= new NHibRepository<User>(NHIBERNATE SESSION);
Until now I used some helper class for creating Nhibernate session and init repository.
Helper class is here:
public class FluentNHibHelper
{
private ISessionFactory _sessionFactory;
public FluentNHibHelper(IPersistenceConfigurer db, Assembly asm)
{
InitializeSessionFactory(db, asm);
}
private void InitializeSessionFactory(IPersistenceConfigurer db, Assembly asm)
{
_sessionFactory = Fluently.Configure()
.Database(db)
.Mappings(m => m.FluentMappings.AddFromAssembly(asm))
.ExposeConfiguration(cfg => new SchemaUpdate(cfg).Execute(true, true))
.BuildSessionFactory();
}
public ISession OpenSession()
{
return _sessionFactory.OpenSession();
}
}
with this class I created repository class:
private const string ConnString =
#"Server=TestMachine\SQLEXPRESS;Database=TEST;Trusted_Connection=True;";
UserRepo = new NHibRepository<User>(
new FluentNHibHelper(MsSqlConfiguration.MsSql2008.ConnectionString(ConnString),
Assembly.GetExecutingAssembly())
.OpenSession());
Now I am confuse I don’t what is the best way for creating repository object in view models.
For example in bootstraper class can I somehow register repository class ?
public class CastleBootstrapper : Bootstrapper<IShellViewModel>
{
private IWindsorContainer _windsorContainer;
protected override void Configure()
{
_windsorContainer = new WindsorContainer();
//register repository class here ???
}
}
Can anybody help me? Thank you very much
Sorry for my english.
I use the following in an ASP.net MVC application. Castle.Windsor takes care of creating the ISession dependency for each repository.
//Located in your application startup
protected IWindsorContainer CreateContainer()
{
container = new WindsorContainer();
container.Install(
new PersistenceInstaller(),
new RepositoryInstaller()
//, other installers here
);
return container;
}
public class PersistenceInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.AddFacility<PersistenceFacility>();
}
}
public class PersistenceFacility : AbstractFacility
{
protected override void Init()
{
NHibernate.Cfg.Configuration config = BuildDatabaseConfiguration();
Kernel.Register(
Component.For<ISessionFactory>()
.UsingFactoryMethod(config.BuildSessionFactory),
Component.For<ISession>()
.UsingFactoryMethod(k => k.Resolve<ISessionFactory>().OpenSession())
.LifeStyle.Trasient
);
}
private NHibernate.Cfg.Configuration BuildDatabaseConfiguration()
{
return Fluently.Configure()
.Database(SetupDatabase)
.Mappings(m => m.HbmMappings.AddFromAssemblyOf<Entity>())
.ExposeConfiguration(ConfigurePersistence)
.BuildConfiguration();
}
protected virtual IPersistenceConfigurer SetupDatabase()
{
return MsSqlConfiguration.MsSql2008
.UseOuterJoin()
.ConnectionString(x => x.FromConnectionStringWithKey("ApplicationServices"))
.ShowSql();
}
protected virtual void ConfigurePersistence(NHibernate.Cfg.Configuration config)
{
SchemaMetadataUpdater.QuoteTableAndColumns(config);
}
protected virtual bool IsDomainEntity(Type t)
{
return typeof(DomainBase).IsAssignableFrom(t);
}
}
public class RepositoryInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(Find().Configure(ConfigureLifeStyle()));
}
private ConfigureDelegate ConfigureLifeStyle()
{
return c => c.LifeStyle.Transient;
}
private BasedOnDescriptor Find()
{
return AllTypes.FromAssemblyContaining<NHRepository>()
.Where(type => type.Name.EndsWith("Repository"))
.WithService
.AllInterfaces();
}
}

Inject into anonymous inner class (GIN)

I have something like this:
request.findAllProjects().fire(new ExtReceiver<List<ProjectProxy>>() {
#Override
public void onSuccess(List<ProjectProxy> response) {
view.setProjects(response);
}
});
It is anonymous inner class of the abstract class ExtReceiver. The ExtReceiver is for handling the errors with an errorHandler which i want to provide.
public abstract class ExtReceiver<T> extends Receiver<T> {
private ErrorHandler errorHandler;
public ExtReceiver() {
}
#Inject
public void setErrorHandler(ErrorHandler errorHandler)
{
this.errorHandler = errorHandler;
}
#Override
public abstract void onSuccess(T response);
#Override
public void onFailure(ServerFailure error) {
errorHandler.exception(error);
}
#Override
public void onViolation(Set<Violation> errors) {
ValidationUtils.processViolation(errors);
}
}
I understand why this can't work, because i use the new Operator. But how could i do something like this. I want to have that anonymous class and not put it in an own file or something.
How could I inject that errorHandler? Thought about staticInjections, but it looked like this does not work too (Maybe because of the inheritance i create with doing an anonymous class)
In the opposite to normal Guice i don't know an injector.getInstance() call.
For information: That is a requestFactory call
Why don't you put the errorHandler parameter into the constructor of your abstract class instead creating a separate setErrorHandler setter, something like this:
public abstract class ExtReceiver<T> extends Receiver<T> {
private ErrorHandler errorHandler;
#Inject
public ExtReceiver(ErrorHandler errorHandler) {
this.errorHandler = errorHandler;
}
}
Declare the bindings:
public class MyClientModule extends AbstractGinModule {
protected void configure() {
bind(ErrorHandler.class).in(Singleton.class);
}
}
Declare a Ginjector for your ErrorHandler class annotating it with the Module:
#GinModules(MyClientModule.class)
public interface MyErrorHandlerInjector extends Ginjector {
ErrorHandler getErrorHandler();
}
and then use it like this:
MyErrorHandlerGinjector injector = GWT.create(MyErrorHandlerGinjector.class);
ErrorHandler errorHandler = injector.getErrorHandler();
request.findAllProjects().fire(new ExtReceiver<List<ProjectProxy>>(errorHandler) {
#Override
public void onSuccess(List<ProjectProxy> response) {
view.setProjects(response);
}
});
I think this should work.

creating a GWT ValueProxy and sending to a service method

I want to call a method on a Service with a ValueProxy param - if I do personProxy.setName("test") and then request.callFn(personProxy).fire(), the name property doesn't get passed to server.
Should I do a request.edit(personProxy) before setting the name or something else?
This is the implementation I'm using:
//somewhere in MyActivity.java ...
PersonProxy cp = requestFactory.myRequest().create(PersonProxy.class);
cp.setName("John Doe");
requestFactory.myRequest().doSomething(cp,"extra_param_value").fire(new Receiver<List<PersonProxy>>() {
#Override
public void onSuccess(List<PersonProxy> response) {
//response from server...
}
});
//------------------------
public interface MyRequestFactory extends RequestFactory {
MyRequest myRequest();
}
//------------------------
#ServiceName(value="com.server.MyService", locator="com.server.MyServiceLocator")
public interface MyRequest extends RequestContext {
public Request<Integer> doSomething(PersonProxy param, String extraParam);
}
//------------------------
public class MyServiceLocator implements ServiceLocator {
public Object getInstance(Class<?> clazz) {
return new MyService();
}
}
//------------------------
public class MyService {
public Integer doSomething(Person param, String extraParam) {
System.out.println("person.name="+param.getName()); ---> prints NULL!!! why?
return 0;
}
}
//------------------------
#ProxyForName(value="com.server.Person")
public interface PersonProxy extends ValueProxy {
String getName();
void setName(String name);
}
//-----------------------
public class Person {
public Person() {
super();
}
protected String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Thanks.
The PersonProxy is being created by one instance of a RequestContext and used in another. Turns out there's a bug in AbstractRequestContext.retainArg() that should have thrown an exception to tell you about the API mis-use. Editable proxies aren't supposed to be usable between different RequestContext instances.
TreeRequest ctx = factory.treeRequest();
PersonProxy person = ctx.create(PersonProxy.class);
person.setName("John Doe");
ctx.doSomething(person, "more stuff");
As discussed on IRC, the -Dgwt.rpc.dumpPayload=true JVM flag can be turned on when trying to diagnose where data is going (or isn't).