Marten - use DI to dispose of database connections - dependency-injection

Using Marten, I got an issue where connections were not being disposed of. I was able to fix these by manually disposing of connections. This is error-prone and I was wondering if there is a better approach.
In this post, it is recommended to:
I'd personally recommend to not do manual disposal of the DocumentSession but let the Dependency Injection container let manage it properly - so eg. use request scope registration for DocumentSession and Singleton for Document Store.
How would I configure this? Currently, the extent of my DI for Marten is to use AddMarten method.

Related

Create orchard session

I need to manipulate with data in separated thread in orchard cms.
Problem is when request ends session and services are disposed.
What is the best way to create db session, or how to manipulate with data after request finish?
EDIT:
I am trying something like this code
var builder = new ContainerBuilder();
builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>)).InstancePerLifetimeScope();
//builder.RegisterInstance(_shellSettings = new ShellSettings { Name = ShellSettings.DefaultName });
builder.RegisterType<TransactionManager>().As<ITransactionManager>().InstancePerLifetimeScope();
builder.RegisterType<SessionFactoryHolder>().As<ISessionFactoryHolder>().InstancePerLifetimeScope();
But i don't know what exactly to register, it throws me error when resolving repository.
Spawning threads on a web server is bad, it reduces its ability to serve many requests simultaneously. You should consider offloading your task to some other process, like a windows service, communicating through MSMQ by example.
Otherwise consider letting your task instantiates and disposes off the services and sessions it needs itself, instead of using those bounded to the request life-cycle. You may need to setup for this a dedicated dependency resolver letting the task explicitly control the lifetime of the objects it requests to the dependency resolver.

What is a Grails "transactional" service?

I'm reading the Grails docs on services which make numerous mention of transactions/transactionality, but without really defining what a transactional service method really is.
Given the nature of services, they frequently require transactional behaviour.
What exactly does this mean? Are transactional methods only those that use JPA/JDBC to communicate with a relational DB, or do they apply to anything covered by JTA?
Is there any reason why I just wouldn't make a service class #Transactional in case it evolves to some day use a transaction? In other words, are there performance concerns to making all service methods transactional?
Grails services are transactional by default - if you don't want a service to be transactional, you need to remove all #Transactional annotations (both Grails' #grails.transaction.Transactional and Spring's #org.springframework.transaction.annotation.Transactional) and add
static transactional = false
If you haven't disabled transactions with the transactional property and have no annotations, the service works the same as if it were annotated with Spring's annotation. That is, at runtime Spring creates a CGLIB proxy of your class and registers an instance of the proxy as the Spring bean, and it delegates to an instance of your actual class to do the database access and your business logic. This lets the proxy intercept all public method calls and start a new transaction, join an existing one, create a new one, etc.
The newer Grails annotation has all of the same settings as the Spring annotation, but it works a bit differently. Instead of triggering the creation of a single proxy, each method is rewritten by an AST transform during compilation, essentially creating a mini proxy for each method (this is obviously a simplification). This is better because the database access and transaction semantics are the same, but if you call one annotated method from another annotated with different settings, the different settings will be respected. But with a proxy, it's a direct call inside the delegate instance, and the proxy is bypassed. Since the proxy has all of the logic to create a new transaction or use other different settings, the two methods will use the first method's settings. With the Grails annotation every method works as expected.
There is a small performance hit involved for transactional methods, and this can accumulate if there are a lot of calls and/or a lot of traffic. Before your code runs, a transaction is started (assuming one isn't active) and to do this, a connection must be retrieved from the pool (DataSource) and configured to turn off autocommit, and make the various transaction settings (isolation, timeout, readonly, etc.) have to be made. But the Grails DataSource is actually a smart wrapper around the "real" one. It doesn't get a real JDBC Connection until you start a query, so all of the configuration settings are cached until then, and then "replayed" on the real connection. If the method doesn't do any database work (either because it never does, or because it exits early based on some condition before the db access code fires), then there's basically no database cost. But if it does, then things work as expected.
Don't rely on this DataSource proxying logic though - it's best to be explicit about which services are transactional and which aren't, and within each service which methods are transactional and which aren't. The best way to do this is by annotating methods as needed, or adding a single annotation at the class level if all methods use the same settings.
You can get more info in this talk I did about transactions in Grails.
First, if your performance concerns are due to the fact your services are transactional then you have reached nirvana. I say this because there are going to be plenty of other bottle necks in your application long before this is a major (or even minor) concern. So, don't fret about that.
Typically in Grails a transaction relates to the transactional state of a database connection or hibernate session. Though it could be anything managed by the JTA with the proper Spring configuration.
In simple terms, it's usually means (by default) a database transaction.

Using private fields in the grails controller

I know that service in grails is singleton by default.
Is it bad practice to use private fields in controller/service? Could anyone explain, why?
Controllers are not singletons by default. They are created for each request. Services are, by default singletons. It's not bad practice to use private fields in Services. It's fairly common that Services have private fields to hold configuration state at runtime.
I suspect your concern is about using private fields as a means of storing state for a particular request within a Service. Which is obviously bad considering there could be N requests being serviced by the Service. So long as you are using private fields to control the service from an application perspective and not a request perspective you will be fine.
Edit (further information)
As stated, services can and often do have private members. However, you should never use these as a means for storing information about the current request being processed. Obviously, since this is a singleton that would cause interleaving issues. Only use private members to store information that is visible across all requests. Typically these will be configuration settings of the service itself.
It's best to make your service stateless in regards to the requests they are processing. Any state you need should be encapsulated in the parameter(s) or input/output of your Service methods. Services should act on data, not the other way around.

How do I monitor my connection to a Naming Service?

I have an application that binds object references to multiple Naming Services. If any of these Naming Services are restarted, I'd like to be able to detect that and rebind my references to it. Right now, the only way I can think of doing it is to periodically poll the Naming Service context object with something like the following (using omniorbpy):
def check_connection(context):
try:
if CORBA.is_nil(context):
return False
if context._non_existent():
return False
except CORBA.Exception:
return False
else:
return True
I know that _non_existent() isn't intended to be used as a "ping" operation, but I can't think of any other way to do it. It would be nice if there was a way to be notified with a callback when the connection is lost without having to constantly poll the service. Any CORBA experts out there have any ideas?
Note: The network architecture and Naming Service implementations are out of my control. So switching to a persistent Naming Service isn't an option unfortunately.
If you can't use a persistent Naming Service then I think your only option is to poll. But I would probably just try to rebind the reference rather than check it or call _non_existant().

J2EE and external URL handlers, having doubts about design

I am developing a J2EE application on Glassfish 3.1 which will use one external library that relies heavily on URLs. The URLs will use a custom protocol (e.g. db:123 where 123 is ID of a record in a database). I am having doubts on how to implement the URL protocol handler (and its URLConnection implementation), because this protocol handler will use EJBs to fetch data from the database.
The db protocol handler needs to be registered globally at the moment of JVM startup through -Djava.protocol.handler.pkgs flag. (I couldn't find a better way to do this in Glassfish.) Anyway, because it is registered at JVM startup, it has no knowledge of any EJBs that that it may call at the moment of opening URL streams. So what I did is create a singleton registry class to which database handlers can be registered. This registry is used by URLConnection whenever a stream is requested (it will search the registry for a database handler and use it to fetch data).
Then, an EJB will register itself as database handler in a #PostConstruct method. This way, any time a db:XXX URL is used, EJBs will be called indirectly to fetch the data.
Somehow I feel that this design is a bit dirty, but I'm very limited because of custom URL handlers. If you have any suggestions or tips that you can give me, that would be great.

Resources